簡體   English   中英

當其中一個用於生成隨機數時,Javascript 中的雙方括號符號如何工作?

[英]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。需要注意這樣的事情

您使用 Math.floor(Math.random()*4) 所做的是為數組提供最多 4 個元素的索引。

我建議你使用 Visual Studio Code 的Quokka插件,看看它是如何工作的。

請參閱下圖,來自 Quokka。

在此處輸入圖像描述

基本上你有三個部分:

backgroundColor = ['red', 'green', 'blue', 'orange'][Math.floor(Math.random() * 4)];
^^^^^^^^^^^^^^^^^
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1. 左手作業
  2. 數組表達式
  3. 帶有另一個表達式的括號表示法中的屬性訪問器

如果您將屬性訪問器與行分開並將其移動到下一行或使用另一個數組表達式而不分隔表達式以防止另一個數組作為屬性訪問器,則會出現問題,例如

 x = [42, 15] [1, 2, 3].forEach(x => console.log(x))

更多閱讀: JavaScript 的自動分號插入 (ASI) 的規則是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM