js通过值获取数组对象对应索引

const nn = [ { a: 'ss' },{ a: 'aa' },{ a : '11'},{ a: '33' },{ a: '88' } ] 我要怎么获取 a = 33的下标

 一、

通过indexOf匹配map返回

const index = nn.map(item => item.a).indexOf('33')

来源:https://zhidao.baidu.com/question/2058630877191630747.html

 

二、

运用findIndex

const index = nn.findIndex(item=>item.a==='33')

 

两种方式的区别在于map的遍历是不可中断的,所以不管是否找到匹配对象都会完整的遍历整个数组对象,findIndex找到匹配对象后就返回结果,不会继续遍历

posted @ 2019-12-16 14:36  四月i  阅读(17456)  评论(0编辑  收藏  举报