可能重复:
Javascript: Determine whether an array contains a value检查数组是唯一
var thelist = new Array();
function addlist(){
thelist.push(documentgetElementById('data').innerHTML);
}
如何我可以检查我推数据不阵列thelist
已经exsist?
可能重复:
Javascript: Determine whether an array contains a value检查数组是唯一
var thelist = new Array();
function addlist(){
thelist.push(documentgetElementById('data').innerHTML);
}
如何我可以检查我推数据不阵列thelist
已经exsist?
var thelist = []; // Use the array literal, not the constructor.
function addlist(){
// get the data we want to make sure is unique
var data = documentgetElementById('data').innerHTML;
// make a flag to keep track of whether or not it exists.
var exists = false;
// Loop through the array
for (var i = 0; i < thelist.length; i++) {
// if we found the data in there already, flip the flag
if (thelist[i] === data) {
exists = true;
// stop looping, once we have found something, no reason to loop more.
break;
}
}
// If the data doesn't exist yet, push it on there.
if (!exists) {
thelist.push(data);
}
}
如果你不关心IE版本8或更低,则可以使用Array.filter
:
var thelist = new Array();
function addlist(){
var val = documentgetElementById('data').innerHTML;
var isInArray = theList.filter(function(item){
return item != val
}).length > 0;
if (!isInArray)
thelist.push(val);
}
或者,你可以使用Array.indexOf
:
var thelist = new Array();
function addlist(){
var val = documentgetElementById('data').innerHTML;
var isInArray = theList.indexOf(val) >= 0;
if (!isInArray)
thelist.push(val);
}
看一看underscore.js
:underscore.js 然后你可以检查数组为
_.contains(thelist, 'value you want to check');
// The full example
var thelist = new Array();
function addlist(){
var data = documentgetElementById('data').innerHTML;
if(!_.contains(thelist, data)) theList.push(data);
}
或可以添加的值到阵列而不关于重复的值,和相加处理结束后,可以通过
theList = _.uniq(theList);
删除重复的元件当然效率较低的第二种方法。
整个库对于这样一个简单的任务来说是矫枉过正的。 – Shmiddty
确实如此,但答案仍然正确,如果OP代码中还有其他功能可以通过库来简化,那么这个答案可能很有用。 –
@MarkThomas它更简单,更简单,但如果你想学习JavaScript或者更喜欢Vanilla JS(比如我),那就不太好了。 – user1431627
如果你不关心IE < 9你也可以使用Array方法“some”。 只要看看这个例子:
var thelist = [1, 2, 3];
function addlist(data) {
alreadyExists = thelist.some(function (item) {
return item === data
});
if (!alreadyExists) {
thelist.push(data);
}
}
addlist(1);
addlist(2);
addlist(5);
console.log(thelist);
一些决定给定约束至少一个元素是否(回调返回值===真)确实存在与否。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some
不妨把一个'打破;''的块if'这就是'for'环 – Ian
内部和内部使用['阵列#indexOf'](http://ecma-international.org /ecma-262/5.1/#sec-15.4.4.14),因为几乎所有的引擎都有它(对于那些没有使用的polyfill)。希望本地实现可能比你的循环更快(这绝不是保证)。 –
@ T.J.Crowder是的,这基本上消除了整个'for'循环的东西,并允许一个/两个班轮。我会发布一个答案,但这个答案在这里基本上是这样。 – Ian