gpt4 book ai didi

javascript - 是在函数作用域还是 block 作用域中?

转载 作者:行者123 更新时间:2023-12-01 01:07:57 24 4
gpt4 key购买 nike

createRandomList 函数中的 randomNumber 变量是作用域还是 block 作用域? for 循环 block 的 i 变量声明是作用域还是函数作用域?在所有类型的循环中,如果我使用 let 键在 for 循环的括号部分中声明变量 ( for(let i = 0; i < something.length; i += 1) {
// something goes in here
}
),则该变量是 block 作用域的,对吗?最后一个问题,在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] + ".") ;
}

最佳答案

Is my randomNumber variable in my createRandomList function function scoped or block scoped?

是的。

Is the i variable declaration for my for loop block scoped or function scoped?

block 作用域为 for 循环。

In for loops, the whole statement is the loop, right?

是的,有点。 for 的变量声明在循环体将在其中执行的 block 作用域(实际上是 EnvironmentRecord)上初始化。

关于javascript - 是在函数作用域还是 block 作用域中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55443755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com