一系列对象中的意外重复输出

时间:2013-06-19 01:30:30

标签: javascript arrays

我遇到以下代码的问题。它旨在从格式为

的对象数组中删除重复项(第三项和最后一项)
{x: val, y: val2}

但是,我偶尔会得到outputs with duplicates (image),例如:

Object {x: 5, y: 0}
Object {x: 7, y: 0}
Object {x: 7, y: 5}
Object {x: 5, y: 2}
Object {x: 2, y: 1}
Object {x: 7, y: 5}

为什么这段代码没有像预期的那样删除重复项?

var mines = [{}];
console.log("\n\n\n\n\n");
for (var i = 0; i < 10; i++){ //for each mine that needs to be made
  var mine = {}; //initalize temporary object
  var dupeerr = false; //set duplication error flag to false 
                       //(will be flipped if loop needs to be re-executed)
  do{
    //generate coordinates for new mine
    //(random int between 0 and max size), then rounded to
    mine.x = Math.round(Math.random()*(8));
    mine.y = Math.round(Math.random()*(9));
    for (var j = mines.length - 1; j >= 0; j--) { //for each mine in array
      if ((mines[j].x == mine.x) && (mines[j].y == mine.y)) { //check for doubles
        dupeerr = true; //flag for re-execution
      } else if (mines[j] != mine) {
        dupeerr = false;
      }
    };
    //console.log(mines);
  } while (dupeerr || bounderr);

  mines[i] = mine;
}
var ans = [];

for (var i = 0; i < mines.length; i++) {
  ans[i] = mines[i];
  var minebtn = document.getElementById(JSON.stringify(ans[i]));
  console.log(ans[i]);
};

2 个答案:

答案 0 :(得分:4)

问题在于你的循环:

for (var j = mines.length - 1; j >= 0; j--) { //for each mine in array
  if ((mines[j].x == mine.x) && (mines[j].y == mine.y)) { // check for doubles
    dupeerr = true; //flag for re-execution
    break; // This should be sufficient to break you out of the for loop on true
  } else if (mines[j] != mine) {
    dupeerr = false;
  }
};

即使找到一个,它也会继续。在下一次尝试时,它可能是错误的并且将dupeerr覆盖为false。

答案 1 :(得分:1)

您可以使用JSON执行此操作。它有点hacky但它​​应该适用于简单的对象:

var arr = [{x:1,y:1}, {x:1,y:2}, {x:1,y:1}, {x:1,y:2}];

function removeDups(arr) {
  return arr
    .map(JSON.stringify)
    .filter(function(v,i,self){ return self.indexOf(v) == i })
    .map(JSON.parse);
}

console.log(removeDups(arr)); //=> [{x:1,y:1}, {x:1,y:2}]