如何使用IndexOf方法获取JS对象数组中的索引

获得数组里某一个对象的索引的最佳方法是什么呢?

比如如下场景:

复制代码
var hello = {
    hello: 'world',
    foo: 'bar'
};
var qaz = {
    hello: 'stevie',
    foo: 'baz'
}

var myArray = [];
myArray.push(hello,qaz);
复制代码

现在我想得到hello属性值是stevie的对象的索引。在这个例子里,它是1

答案:

 使用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')

 

posted @   Ning-  阅读(324)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示