[英]How does the double square bracket notation in Javascript works when one of them is used to generate a random number?
backgroundColor=['red','green','blue','orange'][Math.floor(Math.random()*4)]
有人能解釋一下這段代碼是如何在 Javascript 語法中執行的嗎,我知道它會生成一個隨機數,但結果是第二個方括號中生成的索引值中的顏色。
在 C++ 中,array[][] 用於生成一個二維數組,但這里它生成的是要在第一個方括號對中使用的索引。
希望澄清代碼執行是如何發生的
如果你把它分解成單獨的部分會更容易
const colors = ['red','green','blue','orange']
const randomIndex = Math.floor(Math.random()*4)
// colors.length would be even better than "4"
// Pick a random index from "colors"
backgroundColor = colors[randomIndex]
// or, expanding "randomIndex"
backgroundColor = colors[Math.floor(Math.random()*4)]
// or, expanding "colors"
backgroundColor = ['red','green','blue','orange'][Math.floor(Math.random()*4)]
第一個括號是數組。
第二個括號是您要訪問的索引。
Math.floor(Math.random()*4)
解析為 0 到 4 之間的某個數字
console.log(Math.floor(Math.random()*4))
多維 arrays 可以用嵌套的 arrays 完成,例如:
let arr = [[1,2,3], [3,4,5], [5,6,7]]
有趣的是,您可以使用相同的語法訪問 object 個屬性
let obj = { 1: "hy" } console.log(obj[1])
首先,如果你看到obj[1]
你會認為它是一個數組,但它實際上是一個 object。需要注意這樣的事情
基本上你有三個部分:
backgroundColor = ['red', 'green', 'blue', 'orange'][Math.floor(Math.random() * 4)];
^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
如果您將屬性訪問器與行分開並將其移動到下一行或使用另一個數組表達式而不分隔表達式以防止另一個數組作為屬性訪問器,則會出現問題,例如
x = [42, 15] [1, 2, 3].forEach(x => console.log(x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.