includes方法
includes方法用于判断一个数组或字符串是否包含指定的元素,并返回布尔值。
语法
array.includes(searchElement[, fromIndex])
参数
searchElement:要搜索的元素。fromIndex(可选):开始搜索的索引位置。如果省略该参数,则默认从索引0开始搜索。如果传递的值为负数,则从末尾开始计算索引。
返回值
- 如果数组或字符串包含指定的元素,则返回
true。 - 如果数组或字符串不包含指定的元素,则返回
false。
示例
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('apple')); // true
console.log(fruits.includes('grape')); // false
const str = 'Hello, world!';
console.log(str.includes('Hello')); // true
console.log(str.includes('foo')); // false
console.log(str.includes('world', 7)); // true
我们首先创建了一个名为fruits的数组,并使用includes方法检查数组是否包含特定的元素。然后,我们创建了一个字符串str,并使用includes方法检查字符串是否包含特定的子字符串。最后一个示例演示了如何使用fromIndex参数来指定搜索的起始位置。