js判断数组、对象数组中是否存在某元素

有分享才有进步。

大家都知道判断一个字符串中是否存在某个元素,用 indexOf() 检验 ,如果存在字符串中,返回此元素在字符串中的位置,不存在则返回 -1

示例:

var str = 'abcde';

console.log( str.indexOf('a') ); // 存在字符串中,返回位置 0

console.log( str.indexOf('b') ); // 存在字符串中,返回位置 1

console.log( str.indexOf('x') ); // 不存在字符串中,返回 -1

 

那么,如果是一个数组或对象数组呢,可以用 JavaScript Array对象方法,

Array.indexOf() 搜索数组中的元素,并返回它所在的位置,不存在则返回 -1;

Array.includes() 判断一个数组是否包含一个指定的值,返回 true,否则返回false。

Array.find() 返回符合传入测试(函数)条件的数组元素,否则返回 undefined;

Array.fingIndex()  返回符合传入测试(函数)条件的数组元素索引,否则返回 -1;

Array.some()  检测数组元素中是否有元素符合指定条件(函数)。返回 true,否则返回 false;

数组示例:

var arr = ['cat', 'dog', 'bat'];

// indexOf() 方法
console.log( arr.indexOf('cat') ) // 存在 返回位置 0
console.log( arr.indexOf('dog') ) // 存在 返回位置 1
console.log( arr.indexOf('tiger') ) // 不存在 返回 -1

// includes() 方法
console.log( arr.includes('cat' ) ) // 存在 返回 true
console.log( arr.includes('dog' ) ) // 存在 返回 true
console.log( arr.includes('tiger') ) // 不存在 返回 false

// find() 方法
console.log( arr.find(v => v == 'dog' ) ) // 存在 返回值 dog
console.log( arr.find(v => v == 'tiger') ) // 不存在 返回 undefined

// findIndex() 方法
console.log( arr.findIndex(v => v == 'cat' ) ) // 存在 返回 0
console.log( arr.findIndex(v => v == 'dog' ) ) // 存在 返回 1
console.log( arr.findIndex(v => v == 'tiger') ) // 不存在 返回 -1

// some() 方法
console.log( arr.some(v => v == 'cat' ) ) // 存在 返回 true
console.log( arr.some(v => v == 'dog' ) ) // 存在 返回 true
console.log( arr.some(v => v == 'tiger') ) // 不存在 返回 false

对象数组示例:

var arr = [{name:'cat'}, {name:'dog'}, {name:'bat'}];

console.log( arr.find(v => v.name == 'dog' ) ) // 存在 返回 {name: "dog"}
console.log( arr.find(v => v.name == 'tiger') ) // 不存在 返回 undefined

console.log( arr.findIndex(v => v.name == 'cat' ) ) // 存在 返回 0
console.log( arr.findIndex(v => v.name == 'dog' ) ) // 存在 返回 1
console.log( arr.findIndex(v => v.name == 'tiger') ) // 不存在 返回 -1

console.log( arr.some(v => v.name == 'cat' ) ) // 存在 返回 true
console.log( arr.some(v => v.name == 'dog' ) ) // 存在 返回 true
console.log( arr.some(v => v.name == 'tiger') ) // 不存在 返回 false