本篇文章讲解一下微信小程序中js怎么查找数组中符合条件的元素索引,这里我们用到es6的数组处理该当findIndex
findIndex()
查找数组中符合条件的元素索引,若有多个符合条件的元素,则返回第一个元素索引。
一、普通数组查索引
let arr=[1,2,3,4,5,6]; console.log(arr.findIndex(o=> o==20)) //找不到时返回 -1 console.log(arr.findIndex(o=> o==2)) //返回2的索引是 1 //若有多个符合条件的元素,则返回第一个元素索引。 console.log(arr.findIndex(o=> o>2)) //返回是第一个也就是3的索引 2
二、对象数组查索引
let arr1=[ {name:"张三",age:16}, {name:"张四",age:18}, {name:"王五",age:20}, ] console.log(arr1.findIndex(o=> o.name=="张四")) //返回张四的索引是 1 //若有多个符合条件的元素,则返回第一个元素索引。 console.log(arr1.findIndex(o=> o.age>19)) //返回是第一个也就是王五的索引 2
其它数组相关文章
微信小程序js数组通过join()实现用逗号隔开
微信小程序JS删除数组里的某个元素方法(splice的用法)