如果您只需要检查是否添加了重复项,则可以使用设置大小:
function hasDuplicates<T>(arr: T[]): boolean {
return new Set(arr).size < arr.length;
}
hasDuplicates(["A", "A"]) // true
hasDuplicates(["A", "B"]) // false
您还可以使用代理对象来了解何时添加重复项,因为它们被添加到数组中:
const myArray1 = ["a", "b"];
const myArrayProxy1 = new Proxy(myArray1, {
set: (target, property, value) => {
const exits = target.includes(value);
if (exits) {
console.log(`Duplicate index ${property.toString()}, value: ${value}`);
}
return true;
}
});
myArrayProxy1.push("a", "a", "b", "c");
// Prints:
// Duplicate index 2, value: a
// Duplicate index 3, value: a
// Duplicate index 4, value: b
If您确实想要主动并只使用您的阵列而无需重复,您可以覆盖设置逻辑:
const myArray2 = ["a", "b"];
const myArrayProxy2 = new Proxy(myArray2, {
get: (target, property) => {
return Reflect.get(target.filter(Boolean), property);
},
set: (target, property, value) => {
const exits = target.includes(value);
return exits ? true : Reflect.set(target, property, value);
}
});
myArrayProxy2.push("a", "a", "b", "c");
console.log([...myArrayProxy2]); // - Prints: ["a", "b", "c"]