JavaScript 中获取数组中对象的索引
JavaScript 中要通过特定属性查找数组中对象的索引:
-
在数组上调用
findIndex
方法。 - 检查每个对象是否具有具有特定值的属性。
-
findIndex
方法将返回第一个匹配对象的索引。
const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}];
const index = arr.findIndex(object => {
return object.id === 'b';
});
console.log(index); // 👉️ 1
我们传递给 Array.findIndex
方法的函数会针对数组中的每个元素进行调用,直到它返回真值或遍历数组中的所有元素。
在回调函数的每次调用中,我们检查对象的属性是否等于特定值并返回 true 或 false。
如果我们传递给 findIndex()
方法的函数从未返回真值,则该方法返回 -1。
Internet Explorer
不支持findIndex
方法。 如果我们需要支持浏览器,请使用本文介绍的下一种方法。
要通过特定属性查找数组中对象的索引:
-
使用
map()
方法遍历数组,只返回相关属性的值。 -
对从 map 数组返回的值调用
indexOf()
方法。 -
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,它就可以完成工作。
相关文章
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 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。