迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中获取数组中对象的索引

作者:迹忆客 最近更新:2022/12/19 浏览次数:

JavaScript 中要通过特定属性查找数组中对象的索引:

  1. 在数组上调用 findIndex 方法。
  2. 检查每个对象是否具有具有特定值的属性。
  3. findIndex 方法将返回第一个匹配对象的索引。
const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}];

const index = arr.findIndex(object => {
  return object.id === 'b';
});

console.log(index); // 👉️ 1

我们传递给 Array.findIndex 方法的函数会针对数组中的每个元素进行调用,直到它返回真值或遍历数组中的所有元素。

在回调函数的每次调用中,我们检查对象的属性是否等于特定值并返回 truefalse

如果我们传递给 findIndex() 方法的函数从未返回真值,则该方法返回 -1

Internet Explorer 不支持 findIndex 方法。 如果我们需要支持浏览器,请使用本文介绍的下一种方法。

要通过特定属性查找数组中对象的索引:

  1. 使用 map() 方法遍历数组,只返回相关属性的值。
  2. 对从 map 数组返回的值调用 indexOf() 方法。
  3. indexOf() 方法返回一个值在数组中第一次出现的索引。
const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}];

const index = arr.map(object => object.id).indexOf('c');

console.log(index); // 👉️ 2

我们使用 Array.map 方法获取相关值的数组。

const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}];

const values = arr.map(object => object.id)
console.log(values) // 👉️ ['a', 'b', 'c']

然后我们在数组上调用 Array.indexOf 方法来获取具体值的索引。

由于 map() 方法遍历数组的所有元素,因此元素的顺序得以保留,并且对于值数组和对象数组都是相同的。

如果 indexOf 方法没有找到具有传入值的元素,它会返回 -1,就像 findIndex 方法一样。

这个解决方案绝对不如 findIndex 那样优雅和直接。 但是,如果我们必须支持 Internet Explorer,它就可以完成工作。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便