簡體   English   中英

是在功能范圍內還是在塊范圍內?

[英]Is it in the Function Scope or Block Scope?

我的createRandomList函數中的randomNumber變量是作用域還是塊作用域? for循環塊的i變量聲明是作用域還是函數作用域? 在所有類型的循環中,如果我使用let鍵在a的圓括號部分中聲明一個變量( for(let i = 0; i < something.length; i += 1) { // something goes in here }插入內容for(let i = 0; i < something.length; i += 1) { // something goes in here } )對於循環,變量是塊作用域的,對嗎? 最后一個問題,在for循環中,整個語句是循環,對嗎? 循環不僅是代碼塊,對嗎? 我問,因為有人將整個事物稱為循環,而另一些人則將代碼塊稱為循環。

 function random100() { return Math.floor(Math.random() * 100) + 1; } function createRandomList() { let arr = [] for(let i = 0; i < 10; i += 1) { let randomNumber = random100() ; arr.push(randomNumber) ; } return arr ; } /* console.log(randomNumber) ; <---- Does this not work because you can't access a variable in the local scope from outside the local scope or because let is block scoped? */ let myRandomList = createRandomList() ; for (let i = 0; i < myRandomList.length; i += 1) { console.log("Item " + i + " in the array is " + myRandomList[i] + ".") ; } 

我的createRandomList函數中的randomNumber變量是作用域還是塊作用域?

是。

for循環塊的i變量聲明是作用域還是函數作用域?

塊作用域為for循環。

在for循環中,整個語句就是循環,對嗎?

是的,有點。 for的變量聲明是在for在其中執行循環主體的塊作用域(實際上是EnvironmentRecord)上初始化的。

暫無
暫無

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

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