let example = {
a:20,
b:40,
c:60
}
for(let j=0,i in example){
console.log(example[i]*j);
j++;
}
为什么普通的for循环可以有多个变量声明,但是for-in循环不能?还是我做错了?
您正在编写语法上不正确的代码。
在JavaScript中,不能将
for-in
表达式与任何其他赋值表达式一起使用。
您可以简单地将j=0
分配从for循环中拉出,这应该可以修复错误
let example = {
a:20,
b:40,
c:60
}
let j=0
for(i in example){
console.log(example[i]*j);
j++;
}
我试图更改您的代码,以不在for循环的括号内声明任何变量。我从未见过这样的事情。也许有可能,但是在for循环上方声明一个变量会更简单,像这样(假设这就是您希望执行的操作):
let example = {
a:20,
b:40,
c:60
}
let j=0
for(let i in example){
console.log(example[i]*j);
j++;
}
Edit:如注释中所述:“您可能应该在let
声明之前添加一个i
,否则它将被全局定义。”我刚刚在代码段中做了更改!
在这种情况下,for-loop
中不能有多个表达式。正确的方法是在循环之前声明j
,如下所示:
let example = {
a:20,
b:40,
c:60
}
let j = 0;
for(let i in example){
console.log(example[i]*j);
j++;
}