javascript Array includes()方法
includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。let str = ['abc', 'def', 'ghi'];console.log(str.includes('def'))console.log(str.includes('npm'))运行结果:VM578:2 trueVM578:3 falseincludes的用法...
·
includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。
let str = ['abc', 'def', 'ghi'];
console.log(str.includes('def'))
console.log(str.includes('npm'))
运行结果:
VM578:2 true
VM578:3 false
includes的用法:
arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
searchElement: 必须。需要查找的元素值。
fromIndex: 可选。从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。
如下例子:
let str = ['abc', 'def', 'ghi'];
console.log(str.includes('def',0))
console.log(str.includes('def',3))
console.log(str.includes('npm',4))
运行结果:
VM674:2 true
VM674:3 false
VM674:4 false
从上面可以看出,当fromIndex 大于等于数组长度 ,会返回 false 。该数组不会被搜索。
let str = ['abc', 'def', 'ghi'];
console.log(str.includes('def',0))
console.log(str.includes('def',-3))
运行结果:
VM706:2 true
VM706:3 true
当 fromIndex为负值时,则按升序从 array.length + fromIndex 的索引开始搜索。
但是,如果 array.length + fromIndex 还是为负值时呢?
let str = ['abc', 'def', 'ghi'];
console.log(str.includes('def',0))
console.log(str.includes('def',-10))
运行结果:
VM764:2 true
VM764:3 true
当 array.length + fromIndex 为负值时,则整个数组都会被搜索。
更多推荐
所有评论(0)