Ich möchte ein neues Verfahren zum Array.prototype anbringt:Wie Array-Elemente an Ort und Stelle ersetzen
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]
Die Methode entfernt Duplikate aus einem Array. Das Problem, das ich habe, ist, dass immer wenn uniq
aufgerufen wird, ein neues Array zurückgegeben wird. Ich möchte so etwas wie dies zu tun:
Array.prototype.uniq = function(){
this = this.filter((val, index) => { // "ReferenceError: Invalid left-hand side in assignment
return this.indexOf(val) === index;
});
};
so dass:
var a = [1, 1, 2, 3];
a.uniq();
console.log(a); // output: [1,2,3]
Was soll ich tun?
Warum nicht einfach 'a = a.uniq()'? – Schleis
@Schleis das funktioniert, aber ich bin nur neugierig, wie man es in Prototyp – Cheng
[Wie Elemente im Array mit Elementen eines anderen Arrays ersetzen] (http://stackoverflow.com/questions/17511273/how-to-replace) Elemente in Array mit Elementen eines anderen Arrays – GingerPlusPlus