关于javascript:检查数组是否唯一

Check that the array is unique

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Javascript: Determine whether an array contains a value

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

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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<9,也可以使用数组方法"some"。看看这个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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


看一下underscore.js:underline.js然后您可以检查数组

1
2
3
4
5
6
7
8
_.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);
}

或者可以将值添加到数组中,而不涉及重复值,并且在添加过程完成后,可以通过

1
theList = _.uniq(theList);

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


如果您不关心IE版本8或更低版本,可以使用Array.filter

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
var thelist = new Array();
function addlist(){
    var val = documentgetElementById('data').innerHTML;
    var isInArray = theList.indexOf(val) >= 0;

    if (!isInArray)
        thelist.push(val);
}