怎么在ES6中使用 Array.includes 处理多重条件

本篇文章为大家展示了怎么在ES6中使用 Array.includes 处理多重条件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

具体如下:

includes   [ɪnk'lu:dz]  包含,包括

includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。

举个例子:

// 条件语句
function test(fruit) {
 if (fruit == 'apple' || fruit == 'strawberry') {
 console.log('red');
 }
}

乍一看,这么写似乎没什么大问题。然而,如果我们想要匹配更多的红色水果呢,我们是不是得用更多的 || 来扩展这条语句?

我们可以使用 Array.includes(Array.includes) 重写以上条件句。

function test(fruit) {
 // 把条件提取到数组中
 const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
 if (redFruits.includes(fruit)) {
 console.log('red');
 }
}

我们把红色的水果(条件)都提取到一个数组中,这使得我们的代码看起来更加优雅,整洁。

怎么在ES6中使用 Array.includes 处理多重条件

fromIndex 大于等于数组长度

如果fromIndex 大于等于数组长度 ,则返回 false 。该数组不会被搜索:

var arr = ['a', 'b', 'c'];
arr.includes('c', 3);  //false
arr.includes('c', 100); // false

计算出的索引小于 0

如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。

// 数组长度是3
// fromIndex 是 -100
// computed index 是 3 + (-100) = -97
 
var arr = ['a', 'b', 'c'];
arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true

上述内容就是怎么在ES6中使用 Array.includes 处理多重条件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。