2017-03-23 51 views
0

我想知道如何洗牌數組並返回一個NEW數組。到目前爲止,我已經看到了在堆棧溢出此解決方案:隨機數組並返回一個新的數組JS

How to randomize (shuffle) a JavaScript array?

該解決方案完全在返回相同的陣列洗牌,但我真的不明白爲什麼。任何人都可以解釋這一點,並幫助我修改它,以便它返回一個新的數組?

謝謝!

+0

也許有用,您希望它不會改變你原來的數組,但只返回一個新的(副本)? – ramden

+0

您需要閱讀https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle – Bergi

回答

1

我知道的最簡單的方法來創建一個數組的副本使用:

var newArray = [].concat(originalArray); 

你可以對鏈接的答案執行中的大多數解決方案的第一線,你會得到一個新的陣列與原始不變。這裏是最精彩的答案對鏈接的問題修改後的版本:

function shuffle(originalArray) { 
    var array = [].concat(originalArray); 
    var currentIndex = array.length, temporaryValue, randomIndex; 

    // While there remain elements to shuffle... 
    while (0 !== currentIndex) { 

    // Pick a remaining element... 
    randomIndex = Math.floor(Math.random() * currentIndex); 
    currentIndex -= 1; 

    // And swap it with the current element. 
    temporaryValue = array[currentIndex]; 
    array[currentIndex] = array[randomIndex]; 
    array[randomIndex] = temporaryValue; 
    } 

    return array; 
} 
+1

[帶JavaScript的克隆數組](https://davidwalsh.name/javascript-clone-array)建議' var array = originalArray.slice(0);'。 – Ouroborus

+0

@Ouroborus是的,這是克隆數組的另一種方式。他認爲,我認爲你不應該修改'Array'原型。另外,'concat'看起來要比'slice'快得多:https://jsperf.com/test-slice-vs-concat/1 –

+0

實際上,它在Chrome中速度明顯更快,在Safari中它們大致相當,Firefox 「切片」速度要快得多。哦,瀏覽器...:P –

0

如果你想使用第三方庫,Lodash是這個非常好。

只需使用_.shuffle()即可獲得新陣列。

+0

這個答案沒有解釋任何東西。 – Bergi

0

<p id="output"> 

<script> 
var arrayList= ['a','b','c','d','e','f','g']; 
arrayList.sort(function(){ 
    return 0.5 - Math.random() 
}) 

document.getElementById("output").innerHTML = arrayList; 

</script>