JavaScript查找对象数组中某个元素的下标

25 篇文章 0 订阅

关于JS的数组操作,有很多熟知的方法,比如,forEach, map, filter 等等。但是对于“查找对象数组中某个元素下标”这个需求,今天get了一个新的写法。

下面举两个例子:

var array = [1,2,3,'4'];

var indexOf4 = (array || []).findIndex((item) => item === '4');

console.log(indexOf4); // 3
var profiles= [
    {
      id: 'id123',
      name: "lin",
      age: 23
    },
    {
      id: 'id456',
      name: "lin2",
      age: 12
    },
    {
      id: 'id678',
      name: "lin3",
      age: 13
    }
];

var currentProfile = {
      id: 'id456',
      name: "lin2",
      age: 12
}; 

var currentProfileIndex = (profiles|| []).findIndex((profile) => profile.id === currentProfile .id);

console.log(currentProfileIndex );

findIndex这个方法对于当前的这种需求再适合不过,以后再也不用傻傻的写遍历函数啦。

  • 22
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
JavaScript,可以使用findIndex()方法来获取数组某个元素下标。该方法会在数组从左到右查找,找到第一个满足条件的元素后返回其下标,如果没有找到,则返回-1。 例如,在给定的代码,可以使用findIndex()方法来获取数组元素'4'的下标。代码如下: ```javascript var array = [1, 2, 3, '4']; var indexOf4 = array.findIndex((item) => item === '4'); console.log(indexOf4); // 输出 3 ``` 同样,如果要在对象数组查找某个元素下标,可以使用相同的方法。在给定的代码,可以使用findIndex()方法来获取profiles数组对象currentProfile的下标。代码如下: ```javascript var profiles = [ { id: 'id123', name: "lin", age: 23 }, { id: 'id456', name: "lin2", age: 12 }, { id: 'id678', name: "lin3", age: 13 } ]; var currentProfile = { id: 'id456', name: "lin2", age: 12 }; var currentProfileIndex = profiles.findIndex((profile) => profile.id === currentProfile.id); console.log(currentProfileIndex); // 输出 1 ``` 通过使用findIndex()方法,可以方便地获取JavaScript数组某个元素下标。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [js数组依据下标删除元素](https://download.csdn.net/download/weixin_38543280/13219349)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [js查找对象数组某个元素下标](https://blog.csdn.net/slow097/article/details/124293553)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值