javascript 数组的过滤器数组(子串)

e5nqia27  于 11个月前  发布在  Java
关注(0)|答案(2)|浏览(140)

我有一个数组的数组,我想只显示从搜索栏的子字符串数组。
我的代码:
在第一部分(不显示)我从搜索栏中获取值,并在之前有一个空格(如果没有写入,则查看所有数组)

const Arrays = [
 [
  { text: " first ", image: "1.jpg", },
  " hello"," world"," ",
],
[
  {text: " second",image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",},
  " goodbye"," world"," ",
],
[
  { text: " Salut", image: "bass.jpg", },
  " Ca va"," au revoir"," ",
],
];

const showArrays = Arrays.filter(function(array) {return array.includes(searchimp) })

字符串
这是我的过滤器函数,它的工作,只有当searchchimp是完全相同的元素从一个子数组
与searchchimp我的const从搜索栏。
最后,我有一个函数(不是show)来显示“showArrays”,并格式化每个数组中的第一个元素以显示图片,
它运行,当我写“goodbye”时,它返回第二个数组,但当我写“goo”时,它没有返回任何东西。

fnvucqvd

fnvucqvd1#

要搜索子字符串,可以使用indexOf方法。
要绕过嵌套数组,最好使用some方法

const Arrays = [
  [
    { text: " first ", image: "1.jpg", },
    " hello"," world"," ",
  ],
  [
    {text: " second",image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",},
    " goodbye"," world"," ",
  ],
  [
    { text: " Salut", image: "bass.jpg", },
    " Ca va"," au revoir"," ",
  ],
];
const searchimp = prompt('What find? ')
const showArrays = Arrays.filter(function (array) {
  return array.some(el => { // iterate
    if (typeof el === 'string') { // search in string
      return el.indexOf(searchimp) > -1; // if find, return true and stop iterate
    }
    return false;
  })
})

console.log(showArrays);

字符串
单行记录

const showArrays = Arrays.filter(ar => ar.some(el => typeof el === 'string' ? el.indexOf(searchimp) > -1 : false))

vzgqcmou

vzgqcmou2#

使用Array.some()查找是否存在匹配。使用String::includes()进行匹配:

const Arrays = [
 [
  { text: " first ", image: "1.jpg", },
  " hello"," world"," ",
],
[
  {text: " second",image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",},
  " goodbye"," world"," ",
],
[
  { text: " Salut", image: "bass.jpg", },
  " Ca va"," au revoir"," ",
],
];

const searchimp = 'goo';
const showArrays = Arrays.filter(arr => arr.some(elem => typeof elem === 'string' && elem.includes(searchimp)));

console.log(showArrays);

字符串

相关问题