Javascript 如何就地替换阵列元素
我想将新方法附加到阵列。原型:Javascript 如何就地替换阵列元素,javascript,Javascript,我想将新方法附加到阵列。原型: Array.prototype.uniq = function(){ return this.filter((val, index) => { return this.indexOf(val) === index; }); }; var a = [1, 1, 2, 3]; console.log(a.uniq()); // output: [1,2,3] console.log(a); // output: [1,1,2,3] 该方法从数
Array.prototype.uniq = function(){
return this.filter((val, index) => {
return this.indexOf(val) === index;
});
};
var a = [1, 1, 2, 3];
console.log(a.uniq()); // output: [1,2,3]
console.log(a); // output: [1,1,2,3]
该方法从数组中删除重复项。我遇到的问题是,无论何时调用uniq
,都会返回一个新数组。我想这样做:
Array.prototype.uniq = function(){
this = this.filter((val, index) => { // "ReferenceError: Invalid left-hand side in assignment
return this.indexOf(val) === index;
});
};
以便:
var a = [1, 1, 2, 3];
a.uniq();
console.log(a); // output: [1,2,3]
我该怎么办?如果索引不相同,您可以使用
for
循环遍历数组,并使用splice
Array.prototype.uniq = function () {
// Reverse iterate
for (var i = this.length - 1; i >= 0; i--) {
// If duplicate
if (this.indexOf(this[i]) !== i) {
// Remove from array
this.splice(i, 1);
}
}
// Return updated array
return this;
};
var a = [1, 1, 2, 3];
a.uniq();
console.log(a); // output: [1,2,3]
如果索引不相同,可以使用
for
循环迭代数组,并使用splice
Array.prototype.uniq = function () {
// Reverse iterate
for (var i = this.length - 1; i >= 0; i--) {
// If duplicate
if (this.indexOf(this[i]) !== i) {
// Remove from array
this.splice(i, 1);
}
}
// Return updated array
return this;
};
var a = [1, 1, 2, 3];
a.uniq();
console.log(a); // output: [1,2,3]
为什么不干脆做
a=a.uniq()
?@Schleis肯定行得通,但我只是好奇如何在prototypeThx中实现它为什么不干脆做a=a.uniq()
?@Schleis肯定行得通,但我只是好奇如何在prototypeThx中实现它!我考虑过拼接,但当我从数组中删除元素时,索引会发生变化。反向迭代非常聪明:)不需要返回此
行,对吗?Tushar,for循环中的索引不应该是i-1
,因为i=this.length
使此[i]
脱离循环。Thx!我考虑过拼接,但当我从数组中删除元素时,索引会发生变化。反向迭代非常聪明:)不需要返回此
行,对吗?Tushar,for循环中的索引不应该是i-1
,因为i=this.length
使此[i]
脱离循环。