js filter find 使用及区别

JavaScript07

js filter find 使用及区别,第1张

相同点:使用语法相同  均不改变原数组

array.filter(function(value, index, arr),thisValue)

array.find(function(value, index, arr),thisValue)

value:必须  代表当前元素      index:可选  当前元素索引  

arr:可选 当前数组    thisValue:传递给函数的值,一般用this值,为空时undfined传给this

不同点:find 从数组中查找符合条件的第一个元素并返回。filter从数组中查找符合条件的所有元素并返回数组。

举例:

所以,当查找数组中符合条件的所有元素时用filter,查找数组中符合条件的第一个元素用find。

就是在数组中查找符合条件的第一个元素(成员)。

比如:

[1,2,5,-1,9,-3].find(n=>n<0)

//这是查找数组中第一个小于0的数

//查询结果为-1