我正在使用上面的代码并删除基于id的项目 当我达到最大数组长度时,我在比较i + 1项时没有定义id。 感谢你的帮助......
var arr = [{"id":"0-block-0","left":206.5,"top":0},{"id":"0-block-1","left":446.5,"top":0},{"id":"0-block-2","left":474.5,"top":16},{"id":"0-block-2","left":686.5,"top":0}];
Expecting outout = [{"id":"0-block-0","left":206.5,"top":0},{"id":"0-block-1","left":446.5,"top":0},{"id":"0-block-2","left":686.5,"top":0}]
Array.prototype.unique = function(){
var passNum = this.length;
var _self = this;
// to repeat loops n*n times
while(passNum>0){
for(var i = 0;i<this.length;i++) {
if(this[i].id==this[i+1].id){
var _indx = this.indexOf(this[i]);
this.splice(_indx,1);
}
}
passNum = passNum-1;
}
return this;
};
答案 0 :(得分:0)
您可以使用ES2015套件执行此操作。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
编辑:如果您无法使用ES2015,则可以使用polyfill。