例如,我们有访客来访,我们想记住所有人。但是,反复访问不应导致重复。访客只能被“计数”一次。 使用set就像这样:
const set = new Set();
const sara = { name: 'sara' };
const leyla = { name: 'leyla' };
const mera = { name: 'mera' };
set.add(sara);
set.add(mera);
set.add(leyla);
set.add(sara);
set.add(mera);
for (let user of set) {
console.log(user);
}
我想使用一组用户而不是set 并检查是否重复,我使用arr.find() 这是什么代码?
答案 0 :(得分:1)
要检查已经存在的name
,请使用find
:
if (!arr.some(({ name }) => name === obj.name)) arr.push(obj);
function addUniq(arr, obj) {
if (!arr.some(({ name }) => name === obj.name)) arr.push(obj);
}
const uniqArr = [];
const sara = { name: 'sara' };
const leyla = { name: 'leyla' };
const mera = { name: 'mera' };
addUniq(uniqArr, sara);
addUniq(uniqArr, mera);
addUniq(uniqArr, leyla);
addUniq(uniqArr, sara);
addUniq(uniqArr, mera);
uniqArr.forEach(e => console.log(e));
.as-console-wrapper { max-height: 100% !important; top: auto; }
您还可以将该方法直接添加到Array.prototype
对象上:
Array.prototype.addUniq = function(obj) {
if (!this.some(({ name }) => name === obj.name)) this.push(obj);
}
const uniqArr = [];
const sara = { name: 'sara' };
const leyla = { name: 'leyla' };
const mera = { name: 'mera' };
uniqArr.addUniq(sara);
uniqArr.addUniq(mera);
uniqArr.addUniq(leyla);
uniqArr.addUniq(sara);
uniqArr.addUniq(mera);
uniqArr.forEach(e => console.log(e));
.as-console-wrapper { max-height: 100% !important; top: auto; }