js includes方法 和 filter方法

Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法相似。该方法属于 ES7 ,但 Babel 转码器已经支持数组

[1, 2, 3].includes(2); // true
 
[1, 2, 3].includes(4); // false
 
[1, 2, NaN].includes(NaN); // true
复制代码

该方法的第二个参数表示搜索的起始位置,默认为 0 。若是第二个参数为负数,则表示倒数的位置,若是这时它大于数组长度(好比第二个参数为 -4 ,但数组长度为 3 ),则会重置为从 0 开始。bash

[1, 2, 3].includes(3, 3); // false
 
[1, 2, 3].includes(3, -1); // true
复制代码

没有该方法以前,咱们一般使用数组的indexOf方法,检查是否包含某个值。 ndexOf方法有两个缺点,一是不够语义化,它的含义是找到参数值的第一个出现位置,因此要去比较是否不等于 -1 ,表达起来不够直观。二是,它内部使用严格至关运算符( === )进行判断,这会致使对NaN的误判。ui

filter方法spa

/*
 2     filter()实例:筛选排除掉全部的小值​
 3 
 4     下例使用 filter 建立了一个新数组,该数组的元素由原数组中值大于 10 的元素组成。
 5 
 6 */
 7 
 8 function isBigEnough(element) {
 9     return element >= 10;
10 }
11 var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
12 
13 console.log(filtered);//[ 12, 130, 44 ]
复制代码
相关文章
相关标签/搜索