js判断某数据是否包含某值

判断是否包含了某个数值或字符串

indexOf 没找到指定元素则返回 -1,找到则返回索引值
includes 返回布尔值
hasOwnProperty只用于对象,返回布尔值

字符串

includes、indexOf、startsWith、endsWith

startsWith参数二:搜索起点的位置,默认值为0。判断字符串是否以指定字符开头
endsWith参数二:设置字符串的长度,默认值为str.length。判断字符串是否以指定字符结尾

const str = 'Hello World'
str.includes('World', 5) // truestr.indexOf('World') //6str.startsWith('Hell', 1)
str.endsWith('rld')

对象

hasOwnProperty、in、Reflect.has只检查对象包含这个key

var obj = { age: 18, name: undefined };
obj.hasOwnProperty('age'); // true'name' in obj; // true
Reflect.has(obj, 'name') // trueObject.keys(obj).includes('name')

数组

数组中有多个相同的元素时,只匹配第一个;
includes数组对象不支持比较,请使用some

includes、indexOf、some、find、findIndex

const arr = [1, 2, 3,'san']
arr.includes(2)//truearr.indexOf(2) //1 索引值
arr.indexOf(2) !== -1 //truearr.some(item => item === 2) //true
arr.find(item => item === 2) !== undefined) //true
arr.findIndex(item => item === 2) !== -1   //true