2016-10-20 30 views
2

我試圖定義一個隨機化的方法來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; 

} 

此方法不會返回隨機陣列,但我該如何更改數組本身?

+1

你不能改變'這個' –

+0

那麼在這種情況下我應該怎麼做? –

+1

如果'Math.floor(Math.random()* r.length)'對於每個'e'都是一樣的呢? – joews

回答

2

正如評論所說,在適當的位置更改陣列是一個更好的混洗方式。

但是,如果你確實需要全部更換一次過的元素,你可以使用Array#splice

Array.prototype.randomize = function() { 
    var r = /* the algorithm to get a replacement array... */; 

    this.splice(0, r.length, ...r); 
    return this; 
} 

...spread operator。它是ES2015的一部分。

Spread operator compatibility table

+1

太棒了!問題解決了(儘管我期待着稍後將它放置在其位置上)。 –

2

不可能隨機化在它的位置

Wrong陣列。

如何將'this'設置爲變量數組'r'以便將數組更改爲新數組?

這在JavaScript中是不可能的。你不能覆蓋一個對象,而不是通過this引用而不是通過一個普通的變量,你必須實際改變它的屬性。如果要覆蓋存儲數組引用的變量,則需要明確指定該變量;你不能通過一個方法來實現它(因爲JS不允許通過引用),你只能覆蓋這個引用,而不是所有可能包含它的變量。

+0

**可能的但有點不希望的隨機數組在其位置**,這是因爲我只是想知道如何改變* this *引用,我現在認識到是不可能的,因爲顯然「JS不允許通過-引用。」當然,這完全沒問題。雖然好點! –

相關問題