检查阵列是否唯一

时间:2012-11-16 18:30:53

标签: javascript

  

可能重复:
  Javascript: Determine whether an array contains a value

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

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

4 个答案:

答案 0 :(得分: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);
  }
}

答案 1 :(得分:1)

如果你不关心IE&lt; 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

答案 2 :(得分: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);
}

答案 3 :(得分: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);

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