在前端开发中,数组是我们经常会使用的数据类型之一。在 JavaScript 中,我们经常会使用 indexOf() 和 lastIndexOf() 方法来查找数组中的元素。然而,在 ES7 中,我们有了一个新的方法:Array.prototype.includes。
1. Array.prototype.includes 简介
Array.prototype.includes 是 ES7 中引入的新方法,它用于判断数组中是否包含某个元素。它的语法如下:
arr.includes(valueToFind[, fromIndex])
其中,arr 表示要进行查找的数组,valueToFind 表示要查找的元素值,fromIndex 是可选参数,表示从哪个索引位置开始查找元素。
2. Array.prototype.includes 和 indexOf() 的区别
在 ES6 之前,我们通常使用 indexOf() 方法来查找数组中的元素。indexOf() 方法返回要查找的元素在数组中第一次出现的位置的索引,如果没有找到,则返回 -1。
而在 ES7 中,我们可以使用 Array.prototype.includes 方法来进行查找。和 indexOf() 方法不同的是,includes() 方法返回一个布尔值,表示数组中是否包含该元素。
const arr = [1, 2, 3, 4, 5]; console.log(arr.includes(3)); // true console.log(arr.includes(6)); // false
3. Array.prototype.includes 和 lastIndexOf() 的区别
除了 indexOf() 方法之外,我们还可以使用 lastIndexOf() 方法来查找数组中的元素。lastIndexOf() 方法返回要查找的元素在数组中最后一次出现的位置的索引,如果没有找到,则返回 -1。
和 indexOf() 方法类似,Array.prototype.includes 方法也可以替代 lastIndexOf() 方法。但是,我们需要注意的是,includes() 方法只能判断数组中是否包含该元素,而不能返回该元素在数组中的索引位置。
const arr = [1, 2, 3, 4, 5]; console.log(arr.lastIndexOf(3)); // 2 console.log(arr.includes(3)); // true
4. 实例应用
在实际开发中,Array.prototype.includes 方法可以帮助我们更加方便地进行数组元素的查找。下面是一些实际应用的示例:
4.1 判断字符串中是否包含某个字符
const str = 'hello world'; console.log(str.includes('l')); // true console.log(str.includes('x')); // false
4.2 判断数组中是否包含某个元素
const arr = [1, 2, 3, 4, 5]; console.log(arr.includes(3)); // true console.log(arr.includes(6)); // false
4.3 判断对象数组中是否包含某个对象
-- -------------------- ---- ------- ----- --- - - - ----- ----- ---- -- -- - ----- ----- ---- -- -- - ----- ----- ---- -- -- -- ----- ------ - - ----- ----- ---- -- -- ---------------------------------- -- -----展开代码
在上面的例子中,我们发现,Array.prototype.includes 方法并不能正确地判断对象数组中是否包含某个对象。这是因为 includes 方法内部使用的是 Object.is() 方法进行判断,而不是使用对象的属性进行比较。因此,如果要判断对象数组中是否包含某个对象,我们需要使用其他方法,比如 find() 或者 filter() 方法。
5. 总结
Array.prototype.includes 是 ES7 中引入的新方法,它可以帮助我们更加方便地进行数组元素的查找。和 indexOf() 方法不同的是,includes() 方法返回一个布尔值,表示数组中是否包含该元素。和 lastIndexOf() 方法不同的是,includes() 方法不能返回该元素在数组中的索引位置。
在实际开发中,我们可以使用 Array.prototype.includes 方法来判断字符串、数组、对象数组等数据类型中是否包含某个元素。但是,需要注意的是,如果要判断对象数组中是否包含某个对象,我们需要使用其他方法,比如 find() 或者 filter() 方法。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/65eef91c2b3ccec22f7e5cdf