0

我对以下代码有疑问。它旨在从格式化为的对象数组中删除重复项(第三个和最后一个条目)

{x: val, y: val2}

但是,我偶尔会得到带有重复(图像)的输出,例如:

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]);
};
4

2 回答 2

4

问题是你的 for 循环:

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 覆盖为假。

于 2013-06-19T01:47:18.307 回答
1

你可以用 JSON 做到这一点。这有点骇人听闻,但对于简单的对象应该可以正常工作:

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}]
于 2013-06-19T01:43:40.357 回答