在JavaScript中,如何检查数组是否具有重复的多个值? [英] In JavaScript, how do I check if an array has duplicate multiple values?
本文介绍了在JavaScript中,如何检查数组是否具有重复的多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起,我的英语说得不好.
I'm sorry I can't speak English well.
这些是我的简单代码,带有一些参数数组:
These are my simple code with a few parameters array:
if (link.indexOf({"x" : "1" , "y":"2" , "z": "3"}) === -1) {
link.push({
"x": "1",
"y": "2",
"z": "3"
});
} else {
alert("Duplicate");
}
在"for"循环中使用,但不提示重复".
Used in "for" loop but not alert Duplicate.
推荐答案
您可以为此创建一个单独的函数,以检查列表中是否存在元素.
You can create a separate function for this to check if element exists in list or not.
尝试一下:
function doesExistInList(list, obj) {
for (let i = 0; i < list.length; i++) {
if (list[i].x === obj.x && list[i].y === obj.y && list[i].z === obj.z) {
return true;
}
}
return false;
}
let link = [];
let obj = { "x": "1", "y": "2", "z": "3" };
if (doesExistInList(link, obj) == false) {
link.push(obj);//insert same object to list
} else {
alert("Duplicate");
}
console.log(link);
这篇关于在JavaScript中,如何检查数组是否具有重复的多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文