我試圖定義一個隨機化的方法來Array.prototype
像這樣得到一個新的數組: 的JavaScript array.prototype如何設置「這個」,由一個方法
Array.prototype.randomize = function() { // Yes, this method does cause the array to have 'holes', but its good enough for this example/demonstration
var r = new Array(this.length); // Possible but somewhat unwanted to randomize the array in its place, therefore it has to be set to this new array later on.
this.forEach(function(e) {
r[Math.floor(Math.random() * r.length)] = e;
});
// how do I set 'this' to the variable r? (In order to change the array to the new and randomized array 'r')
return r;
}
此方法不會返回隨機陣列,但我該如何更改數組本身?
你不能改變'這個' –
那麼在這種情況下我應該怎麼做? –
如果'Math.floor(Math.random()* r.length)'對於每個'e'都是一樣的呢? – joews