filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
callback 被调用时传入三个参数:
- 元素的值
- 元素的索引
- 被遍历的数组本身
filter 不会改变原数组,它返回过滤后的新数组。
回调函数只会在已经赋值的索引上被调用,对于那些已经删除或者没有赋值的索引不会被调用。