从MDN JavaScript参考页面的for...of条语句中看到了这一小段,在描述部分的结尾,它说:
您可以使用析构为多个局部变量赋值,或使用类似for (x.y of iterable)的属性访问器将值赋给对象属性.
什么意思?您不能使用x.y
语法来定义for...of
语句中的local variable.
我在一个使用node的简短脚本文件中逐字try 了这一点.错误消息为ReferenceError: x is not defined
我错过了什么?
从MDN JavaScript参考页面的for...of条语句中看到了这一小段,在描述部分的结尾,它说:
您可以使用析构为多个局部变量赋值,或使用类似for (x.y of iterable)的属性访问器将值赋给对象属性.
什么意思?您不能使用x.y
语法来定义for...of
语句中的local variable.
我在一个使用node的简短脚本文件中逐字try 了这一点.错误消息为ReferenceError: x is not defined
我错过了什么?
您可以使用解构为多个局部变量赋值,
这意味着我们可以在for循环中分解对象array.
For example,个个
const iterable = [{a:'1', b:'10'}, {a:'2', b:'20'}, {a:'3', b:'30'}];
for (let {a, b} of iterable) {
console.log(a);
console.log(b);
}
或者使用像for(Iterable的X.Y)这样的属性访问器将 值设置为对象属性.
这意味着我们可以使用属性访问器将数组中的值赋给对象的属性.
For example,个个
const iterable = [{a:'1', b:'10'}, {a:'2', b:'20'}, {a:'3', b:'30'}];
let obj = {iterateValue:'', anyOtherValue:'Anything'}
// let obj = {}
// can be an empty object
for (obj.iterateValue of iterable) {
console.log(obj);
}
You can't have x.y syntax for defining the local variable in a for...of statement.个
您需要在for循环之前定义对象x.不是在for...of statement
米之内.
ReferenceError: x is not defined个
这个错误意味着你还没有定义x并试图使用它.你需要在for循环之前定义它.