JS 判断字符串、数组、对象数组是否包含某个值

一、字符串

var str = 'Hello world!';
console.log( str.indexOf('e') ); // 存在字符串中,返回位置 1
console.log( str.indexOf('d') ); // 存在字符串中,返回位置 10
console.log( str.indexOf('x') ); // 不存在字符串中,返回 -1

二、数组

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

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

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

    Array.findIndex()  返回符合传入测试(函数)条件的数组元素索引,否则返回 -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'}];
var arr2 = [{name:'cat'}, {name:'dog'}]
 
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
 
// 循环判断arr与arr2是否有相同元素,相同的添加isdelete:false字段,不同添加isdelete:true
this.arr.map((item) => {
  let bool = this.arr2.findIndex((it) => {
    return item.name == it.name
  })
  if (bool !== -1) {
    item.isdelete = false
  } else {
    item.isdelete = true
  }
})
 

猜你喜欢

转载自blog.csdn.net/weixin_47127256/article/details/126499771