[英]Why does the math.random function not return a new random element from my array each time?
[英]math.random return array function f
我不太應該如何創建math.random函數。 我仍然對函數以及何時使用循環或函數中如何使用循環還不熟悉。 任何建議都會有所幫助。 謝謝。
friends
的變量,並將其分配給您選擇的數據結構。 Math.random
的文檔: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random 編寫一個使用我們的animals
數組並使用Math.random
返回隨機元素的函數
var animal = {}; animal.species = "bird"; animal["name"] = "eagles"; animal.noises = []; console.log(animal); //Steps 3 var noises = []; noises[0] = "quack"; noises.push("oink"); noises[noises.length] = "bark"; console.log(noises.length); console.log(noises.length-1); console.log(noises); //Step 4 animal.noises = noises; animal.noises.push("meow"); console.log(animal); //Step 6 var animals = []; animals.push("animal"); vconsole.log(animals); var duck = { species: 'duck', name: 'Jerome', noises: ['quack', 'honk', 'sneeze', 'woosh'] }; animals.push(duck); console.log(animals); var coco = { species: 'dog', name: 'bob', noises: ['high', 'low'] }; var bubbles = { species: 'cat', name: 'jim', noises: ['quiet', 'loud'] }; animals.push(coco, bubbles); console.log(animals); //Step 7
Math.random()將您帶到一半! 您只需要在將math.random()的[0,1]輸出擴展為[0,X]時將其四舍五入為整數,其中X是您數組的長度!
如果您有一個動物數組= [獅子,老虎,熊],索引為[0,1,2],則可以返回如下所示的隨機動物:
randomNumber = Math.floor(Math.random()* arr.length)。
math.random()返回0到1之間的值,因此您應乘以3(數組長度)以得到0到3之間的值,然后應使用Math.floor將該randomNumber強制為整數。
然后由animal [randomNumber]返回隨機動物。 說得通?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.