Javascript | Set中的唯一对象 [英] Javascript | Unique object in Set
问题描述
如何阻止 Set
对象填充重复对象?
How can I prevent a Set
object from being populated with duplicate objects?
[
{
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。
So while looping through the array I check if the Set object contains a duplicate, but event if it does, check returns false all the time.
let s = new Set();
//for loop starts here
let check = s.has(obj) // false
if(check == false){
s.add(obj);
}
推荐答案
通过引用传递对象,这意味着当你将它们添加到集合中时,即使它们完全相同,如果用 ===
进行检查,它们也不会相同。
Objects are passed by reference, which means that when you add them to a set, even if they are exactly the same, they will not be the same if you check them with ===
.
var a = {val1: 'hello', val2: 'there'}
var b = {val1: 'hello', val2: 'there'}
console.log(a === b) // false
console.log(a == b) // false
要解决此问题,您可以编写如下内容,取自这篇文章。
To solve this problem, you could write something like the following, taken from 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
使用此算法将检查实际值对象而不是引用。
Using this algorithm will check the actual values of the objects rather than the references.
console.log(isEquivalent(a, b)) // true
这篇关于Javascript | Set中的唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!