1

可能重复:
Javascript:确定数组是否包含值

var thelist = new Array();
function addlist(){
thelist.push(documentgetElementById('data').innerHTML);
}

如何检查我推送的数据是否已存在于数组中thelist

4

4 回答 4

4
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);
  }
}
于 2012-11-16T18:34:09.340 回答
1

如果您不关心 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);​

http://jsfiddle.net/C7PBf/

一些确定是否存在至少一个具有给定约束的元素(回调返回值 === true)。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some

于 2012-11-16T18:45:35.483 回答
0

如果您不关心 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);
}
于 2012-11-16T18:36:41.157 回答
0

看看underscore.jsunderscore.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);

第二种方法当然效率较低。

于 2012-11-16T18:41:12.393 回答