javascript 從一組陣列中隨機取出一項

森林蘑菇_mushroom發表於2017-10-26

設計隨機數

function selectNum( smallNum, BigNum) { 
    var youAll = BigNum - smallNum + 1; 
    return Math. floor( Math. random() * youAll + smallNum); 
}
var fruits = ["apple", "lemon", "banana", "pear", "watermelon", "honeydew", "pen"];
var fruit = fruits[ selectNum( 0, fruits. length- 1)];
console.log( fruit);複製程式碼
  • 可以方便的從陣列中取出隨機的一項

相關文章