【发布时间】:2020-07-15 16:22:43
【问题描述】:
当我尝试使用 for 循环时,这段代码失败了
class TestA {
testArray = [];
constructor() {
this.testArray.push({
name: "joe",
age: 70
});
this.testArray.push({
name: "mike",
age: 50
});
this.testArray.push({
name: "bob",
age: 33
});
}
testLoop() {
for (test of this.testArray) {
console.log(" >>> " + test.name + " " + test.age);
}
}
}
var a = new TestA();
a.testLoop();
错误:
Uncaught ReferenceError: test is not defined
我可以通过使用不同类型的循环来解决这个问题,但不明白为什么这不起作用?
【问题讨论】:
-
for (const test of this.testArray) -
也许把
test of改成let test of? -
应该是:
for (let test of ....) -
我要指出,您不需要多次连续调用
.push()。只需将所有对象作为参数添加到单个调用中,它们都会被添加到数组中。this.testArray.push({...}, {...}, {...}) -
@Coder547:我认为在
class定义中,您是在严格模式 下运行的,它设置了更严格的要求。在class之外,您可以使用"use strict"声明性手动将代码置于该模式。
标签: javascript