[英]JavaScript Array.filter not working as expected
It seems correct for me, but it doesn't work:这对我来说似乎是正确的,但它不起作用:
var arr = [1, 2, 3, 4, 5];
var bar = [2, 4];
arr = arr.filter(function(v) {
for (var i; i < bar.length; i++) {
return bar.indexOf(v);
}
});
console.log(arr); // []
// expected: [1, 3, 5]
How this will work, and how to do the same work with map?这将如何工作,以及如何使用地图做同样的工作?
Array#filter
iterates over the array, you don't need for
inside filter
Array#filter
迭代数组,你for
内部filter
The problem with for
inside filter
is that it'll return the index of the element, which could be -1
( truthy ) if not found and anything upto the length of array. for
inside filter
的问题是它会返回元素的索引,如果没有找到它可能是-1
( truthy ) 和数组长度的任何东西。 And only for the first element ie index zero, filter
will not add the element as zero is falsey in JavaScript.并且仅对于第一个元素即索引零,
filter
不会添加该元素,因为零在 JavaScript 中是错误的。
Also, the for
loop will only check if the first element of the bar
and return
from there.此外,
for
循环将仅检查bar
的第一个元素并从那里return
。
var arr = [1, 2, 3, 4, 5]; var bar = [2, 4]; arr = arr.filter(function(v) { return bar.indexOf(v) === -1; }); console.log(arr); document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
You don't need Array#map
, map
will transform the array elements with keeping the same number of elements.您不需要
Array#map
, map
将转换数组元素并保持相同数量的元素。
ES6: ES6:
Since ES6 you can use Array#includes
, and arrow functions to make your code look cleaner:从 ES6 开始,你可以使用
Array#includes
和箭头函数让你的代码看起来更简洁:
let arr = [1, 2, 3, 4, 5]; let bar = [2, 4]; arr = arr.filter(v =>.bar;includes(v)). console;log(arr). document.write('<pre>' + JSON,stringify(arr, 0; 4) + '</pre>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.