gpt4 book ai didi

Javascript |集合中的唯一对象

转载 作者:行者123 更新时间:2023-11-30 09:21:33 24 4
gpt4 key购买 nike

如何防止 Set 对象被重复对象填充?

  [    
{
prop1: [{value: "val", disabled: true}] (1)
prop2: [{value: [4, 5], disabled: true}] (1)
prop3: [{value: "someOtherValue", disabled: true}] (1)
},

{
prop1: [{value: "val", disabled: true}] (1)
prop2: [{value: [4, 5], disabled: true}] (1)
prop3: [{value: "someOtherValue", disabled: true}] (1)
},
{
prop1: [{value: "otherValue", disabled: true}] (1)
prop2: [{value: [3], disabled: true}] (1)
prop3: [{value: "", disabled: true}] (1)
},
]

因此,在遍历数组时,我会检查 Set 对象是否包含重复项,但即使包含重复项,检查也会始终返回 false。

let s = new Set();

//for loop starts here

let check = s.has(obj) // false

if(check == false){
s.add(obj);
}

最佳答案

对象是通过引用传递的,这意味着当你将它们添加到一个集合中时,即使它们完全相同,如果你用===检查它们也不会相同。

var a = {val1: 'hello', val2: 'there'}
var b = {val1: 'hello', val2: 'there'}
console.log(a === b) // false
console.log(a == b) // false

要解决此问题,您可以编写如下内容,摘自 this article .

var a = {val1: 'hello', val2: 'there'};
var b = {val1: 'hello', val2: 'there'};

function isEquivalent(a, b) {
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);

// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
return false;
}

for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];

// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
return false;
}
}

// If we made it this far, objects
// are considered equivalent
return true;
}

console.log(a === b); // false
console.log(a == b); // false
console.log(isEquivalent(a, b)); // true

使用此算法将检查对象的实际值而不是引用。

console.log(isEquivalent(a, b)) // true

关于Javascript |集合中的唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317553/

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