此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"
答案 0 :(得分:3)
过滤器线基本上添加了另一个循环。它应该是
names = searchWords.filter(x => students.indexOf(x) !== -1);