将for循环转换为数组过滤器

时间:2017-06-23 00:24:03

标签: javascript arrays

此javascript代码尝试使用array.filter以获得更好的性能,而不是for循环“我猜”。无论如何,结果是不一样的,当它被预期时。 它会尝试找出students数组中包含的searchWords的名称 任何想法为什么?thx

let searchWords = ['john','matt','marry'];
let students = ['matt','jack'];
let names = [];
for (let i = 0; i < searchWords.length; i++) {
   if (students.indexOf(searchWords[i]) !== -1) {
       names.push(searchWords[i]);
   }
}
console.log(names.length); // => 1 "correct"

names = [];
names = searchWords.filter(x => students.filter(y => students.indexOf(x) !== -1));
console.log(names.length); // => 3 "incorrect"

1 个答案:

答案 0 :(得分:3)

过滤器线基本上添加了另一个循环。它应该是

names = searchWords.filter(x => students.indexOf(x) !== -1);