Array.prototype.foo = function() {
this = [ "random", "static", "replacement" ];
}
originalArray = [ "this", "was", "here", "first" ];
originalArray.foo();
console.log( originalArray ); // [ "random", "static", "replacement" ];
Zastanawiam się, jak zrobić powyższe.
Edycja oryginalnej tablicy, stosując do niego metodę. Do tej pory wszystko, co mogę zrobić, to:
Array.prototype.foo = function() {
var arr = [ "random", "static", "replacement" ];
return arr;
}
originalArray = [ "this", "was", "here", "first" ];
originalArray = originalArray.foo();
0
user3387566
15 sierpień 2014, 15:55
3 odpowiedzi
Najlepsza odpowiedź
Usuń oryginalną tablicę, a następnie użyj push
Array.prototype.foo = function() {
this.length = 0;
this.push( "random", "static", "replacement" );
}
Jak powiedział Vumbe, jeśli wejście jest tablicą, można użyć apply
funkcja.
Array.prototype.foo = function() {
this.length = 0;
var newArray = ["random", "static", "replacement"];
this.push.apply(this, newArray);
}
2
parchment
15 sierpień 2014, 12:19
Array.prototype.foo = function() {
this.length = 0; //this clears the array
this.push("random");
this.push("static");
this.push("replacement");
}
0
Karolis Juodelė
15 sierpień 2014, 12:01
Możesz użyć .Splice (), aby zmodyfikować tablicę.
Array.prototype.foo = function() {
this.splice(0,this.length,"random","static","replacement");
}
0
David P. Caldwell
15 sierpień 2014, 12:01