我一直在使用具有某種功能的遺留代碼,它應該爲數組返回一個隨機項,而我看到下面的表達式:「Math.random()* arr.length | 0」如何爲數組返回一個隨機索引
array[Math.random() * arr.length | 0]
我的第一印象是嘗試已瞭解the |
operator,但我無法弄清楚如何做的工作。 我測試的鉻控制檯中的表達,我看到總是返回與此有效的索引:
let array = [1,2,3,4]
for(let i = 0; i < 5000; i++){
console.log(array[Math.random() * arr.length | 0]);
}
「的Math.random()* arr.length | 0」是如何工作的回報,隨機指數數組?
哦!它只是一個黑客coerse int整數!謝謝! –
Yeap,實際上,最好使用'Math.trunc()'來代替,意圖更清晰。 –
是的,我會用它。感謝您的建議。 –