判断数组对象中是否包含某一个元素(四种方法)

您所在的位置:网站首页 js判断对象是否有值 判断数组对象中是否包含某一个元素(四种方法)

判断数组对象中是否包含某一个元素(四种方法)

2023-11-10 12:16| 来源: 网络整理| 查看: 265

dataList: [ { id: 1, name: 'name01', age: 16 }, { id: 2, name: 'name02', age: 18 }, { id: 3, name: 'name03', age: 20 } ]

  方法1:findIndex()  

  如果存在 返回目标元素的索引 反之 返回 -1

const res01 = this.dataList.findIndex(item => item.age == 20) const res02 = this.dataList.findIndex(item => item.age == 23) console.log(res01, res02); // 打印结果 2 -1

  方法2: find()

  如果存在 则返回目标元素 反之 返回undefined

const res01 = this.dataList.find(item => item.age == 20) const res02 = this.dataList.find(item => item.age == 23) console.log(res01, res02); // 打印结果 // { undefined // id: 3, // name: 'name03', // age: 20 // }

  方法3:filter()

  如果存在 返回包含目标元素的数组 反之 返回空数组

const res01 = this.dataList.filter(item => item.age == 20) const res02 = this.dataList.filter(item => item.age == 23) console.log(res01, res02); // 打印结果 // [{...}] []

  方法4:some()

  如果存在 返回true 反之 返回false

  

const res01 = this.dataList.some(item => item.age == 20) const res02 = this.dataList.some(item => item.age == 23) console.log(res01, res02); // 打印结果 // true false



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3