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) を持つ要素が少なくとも 1 つ存在するかどうかを判断します。

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

于 2012-11-16T18:45:35.483 に答える
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);

もちろん、2番目の方法は効率的ではありません。

于 2012-11-16T18:41:12.393 に答える
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 に答える