es6中常用的数组用法-判断某个元素是否在数组中

判断数组中是否有某个元素

includes其实更具有语义性,所以在后面的编码过程中,将之前习惯用indexOf的代码改成目前的includes

6. array.includes(searchElement, fromIndex);

includes() 方法用来判断一个数组是否包含一个指定的值,返回 true或 false。searchElement:要查找的元素;fromIndex:开始查找的索引位置。

[1, 2, 3].includes(2, 2);
// false
7. array.indexOf(searchElement[, fromIndex = 0]);

返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。searchElement:要查找的元素;fromIndex:开始查找的索引位置。

[2, 9, 7, 8, 9].indexOf(9);
// 1

良好的编码习惯

一个典型的例子是查看数组是否包含某个元素。 我从来不喜欢使用array.indexOf(item)!== -1来检查。

ES6 及以后版本的功能要强大得多,可以使用新的语言特性安全地重构许多技巧。

clipboard.png

ES6 中可以使用 array.includes(item) 来代替 array.indexOf(item) !== -1

评论

暂无评论