3

js如何查找对象数组中某个对象的下标,已知对象的某个属性值

 8 months ago
source link: https://viencoding.com/article/320
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

js如何查找对象数组中某个对象的下标,已知对象的某个属性值

2023-12-04 06:22:50   前端

要根据value查找其在数组bcsArr中的位置,您可以使用 JavaScript 的 findIndex 方法。这个方法会返回数组中满足提供的测试函数的第一个元素的索引。如果没有元素满足测试函数,则返回-1。

假设您已知value,以下是查找其在bcsArr中位置的代码示例:

const bcsArr = [
    { value: 1, showValue: '1 非常瘦' },
    { value: 2, showValue: '2 过瘦' },
    { value: 3, showValue: '3 标准' },
    { value: 4, showValue: '4 过胖' },
    { value: 5, showValue: '5 非常胖' }
];

const valueToFind = 3; // 假设我们要找的value是3

const index = bcsArr.findIndex(item => item.value === valueToFind);

console.log(index); // 如果找到,输出位置索引;如果没找到,输出-1

在这个例子中,findIndex方法会遍历bcsArr数组,查找其元素的value属性是否等于valueToFind。如果找到匹配的元素,它会返回该元素的索引;如果没有找到,它会返回-1。

viencoding.com版权所有,允许转载,但转载请注明出处和原文链接: https://viencoding.com/article/320 欢迎小伙伴们在下方评论区留言 ~ O(∩_∩)O
文章对我有帮助, 点此请博主吃包辣条 ~ O(∩_∩)O


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK