Array.prototype.filter ( callbackfn [ , thisArg ] )
原文:
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean
value true or false. filter calls callbackfn once for each element in the array, in ascending order, and
constructs a new array of all the values for which callbackfn returns true. callbackfn is called only for elements of
the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not
provided, undefined is used instead.
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being
traversed.
filter does not directly mutate the object on which it is called but the object may be mutated by the calls to
callbackfn.
The range of elements processed by filter is set before the first call to callbackfn. Elements which are
appended to the array after the call to filter begins will not be visited by callbackfn. If existing elements of the
array are changed their value as passed to callbackfn will be the value at the time filter visits them; elements
that are deleted after the call to filter begins and before being visited are not visited.
总结:
1. 回调函数接收三个参数(当前元素的值,当前元素的索引,被筛选的数组),并且有一个返回值(true或false)
2. 数组中的每一个元素(已赋值的,未赋值和已删除的不调用)filter都会为它调用一次回调函数,并且利用返回的true的元素创建一个新的数组。
3. filter 不会改变被筛选的数组(返回一个新数组),但是数组可能会在callback中被改变
4. 如果为 filter 提供一个 thisArg 参数,则它会被作为 callback 被调用时的 this 值。否则,callback 的 this 值在非严格模式下将是全局对象,严格模式下为 undefined。
5. filter 遍历的元素范围在第一次调用 callback 之前就已经确定了。在调用 filter 之后被添加到数组中的元素不会被 filter 遍历到。如果已经存在的元素被改变了,则他们传入 callback 的值是 filter 遍历到它们那一刻的值。被删除或从来未被赋值的元素不会被遍历到。
示例:
var data=[{a:1},{a:2},{},{a:1},{b:1}];
var newData = data.filter(item =>{
return item.a === 1; //筛选出a为1的元素
})

本文介绍了JavaScript中Array.prototype.filter方法。该方法的回调函数接收三个参数,返回布尔值。filter为数组中每个已赋值元素调用回调函数,用返回true的元素创建新数组,不改变原数组,但回调可能改变。遍历范围在首次调用前确定,新增元素不遍历,改变元素按遍历时刻值处理。

855

被折叠的 条评论
为什么被折叠?



