[英]How do I replace the “var” keywords in this code with “let” and “const”?
[英]How do I mix let and var in a for loop?
我使用的是for循環,其中一個變量必須在循環后仍然存在。 在這種情況下是否可以使用let-它似乎不起作用。
for (var data=[],let i=0; i<1000; ++i) {
// Do something here that populates the data variable.
}
或者我應該像這樣在循環外初始化數據變量:
var data = [];
for (let i=0; i<1000; ++i) {
// Do something here that populates the data variable.
}
是的,您應該在循環外聲明另一個變量,而不是使用var
:
let data = []; for (let i = 0; i < 1000; ++i) { data.push(i); } console.log(data);
您只能在一個語句中使用一個聲明var
或let
或const
, 即使在通常情況下,也可以在for循環外使用
即
var data = [], i = 0;
要么
let data = [], i = 0;
這就是為什么您的第二個片段更有意義的原因
let data = []; //make it var if it needs a function-wide scope
for (let i=0; i<1000; ++i) {
// Do something here that populates the data variable.
}
如果在for循環內聯中將data
聲明為let
,則外部將無法訪問data
for (let data = [], i=0; i<1000; ++i) {
// Do something here that populates the data variable.
}
console.log(data); //Uncaught ReferenceError: data is not defined
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.