![e1b438bcf24d0496e3aed89591944b10.png](https://i-blog.csdnimg.cn/blog_migrate/86129c14cad3f2c8da15967e156ff601.jpeg)
问题:indexOf method in an object array?
一个叫Antonio Laguna的老兄问了这个问题,原文大意如下:
What's the best method to get the index of an array which contains objects?
获得数组里某一个对象的索引的最佳方法是什么呢?
Imagine this scenario:
比如如下场景:
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello,qaz);
Now I would like to have the indexOf the object which hello property is 'stevie' which, in this example, would be 1.
现在我想得到hello属性值是stevie
的对象的索引。在这个例子里,它是1
I'm pretty newbie with JavaScript and I don't know if there is a simple method or if I should build my own function to do that
我是一个刚刚新鲜出炉的JavaScript新手,我不知道是否有简单的现成方法,还是需要我自己写一个
答案:
接受的高赞答案
I think you can solve it in one line using the map function
使用map函数,一行帮你搞定
pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');
旁白:这行代码虽然简洁漂亮,而且真的使用到了indexOf
函数,但是对于大数组,特别是频繁更新的大数组,那效率也忒低了点。于是有人提出findIndex
才是更好的选择
另一个答案:
In ES2015, this is pretty easy:
myArray.map(x => x.hello).indexOf('stevie')
or, probably with better performance for larger arrays:
myArray.findIndex(x => x.hello === 'stevie')
【码农爱英语】StackOverflow精选系列背后的故事
作为一个时刻需要和国际接轨的码农来说,英语的重要性毋庸置疑。但是吃青春饭,996是福报,007是福祉的行业,怎么忙里偷闲的学习英语的同时又能学到技术,来延长自己的职业生涯呢?作为上有老,下有小,中间有房贷的无为中年码农更是痛苦万分!英语阅读APP也用了好几款,最后都没有坚持下来。经过一段时间的考量后决定自己写一款英语阅读小程序,因为要兼顾学习英语的同时也能学到技术,我们总是希望一份时间多份收获嘛,所以文章的最佳来源自然是高质量的StackOverflow问答,希望有一天能自由自在的和国际同行们有问有答。
同时,为了学习效果最大化,亦学亦教,所以我也挑选了一些自己略懂的领域的热门问答尝试翻译,还望多多赐教...