gpt4 book ai didi

javascript - Array.indexOf() 的行为

转载 作者:行者123 更新时间:2023-12-02 23:06:24 25 4
gpt4 key购买 nike

Array.IndexOf()函数对于字符串和对象的行为有所不同。

stringBehaviour();
objectBehaviour();

function stringBehaviour() {
let s1 = "helmet";
let s2 = "trousers";
let collection = [];
collection.push(s1);
collection.push(s2);
console.info(collection.indexOf("trousers"));
};

function objectBehaviour() {
let obj1 = {item: "helmet"};
let obj2 = {item: "trousers"};
let collection = [];
collection.push(obj1);
collection.push(obj2);
console.info(collection.indexOf({item: "trousers"}));
};

我该怎么做才能拥有indexOf()不寻找相同的实例,而是寻找对象元素的相等性,以便函数 objectBehaviour()会返回1?

最佳答案

您可以使用 findIndex 来代替,并传递一个按属性比较对象的函数。

stringBehaviour();
objectBehaviour();

function stringBehaviour() {
let s1 = "helmet";
let s2 = "trousers";
let collection = [];
collection.push(s1);
collection.push(s2);
console.info(collection.indexOf("trousers"));
};

function objectBehaviour() {
let obj1 = {item: "helmet"};
let obj2 = {item: "trousers"};
let collection = [];
collection.push(obj1);
collection.push(obj2);
console.info(collection.findIndex(el => isIdentical(el, { item: "trousers"})));
};

function isIdentical(current, given) {
return Object.keys(given).every((key) => current[key] === given[key]);
}

关于javascript - Array.indexOf() 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57577545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com