赋值循环失败:"未定义变量"

时间:2018-02-27 12:41:11

标签: javascript

var xyz, i, tx = {}
// Doesn't work: var xyz, i, tx = {}

for (var i = 0; i < 5; i++) {
    // Doesn't work: window.xyz, window.i, window.tx
    xyz[i].tx = 5
    // Doesn't work: xyz[i]["tx"] = 5
}

alert(xyz);

返回TypeError: xyz is undefined

我定义了变量,尝试强制作用域,尝试了两种不同的方法来调用数组。我不明白。如何让它在循环中编写变量。

2 个答案:

答案 0 :(得分:2)

根据您为每个索引创建对象的意图,您可以初始化数组push并使用函数var xyz = []; for (var i = 0; i < 5; i++) xyz.push({'tx': 5}); console.log(xyz);添加新元素。

&#13;
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
Array
&#13;
&#13;
&#13;

另一种直接的方法是使用类from和函数var xyz = Array.from({length: 5}, (x) => ({'tx': 5})); console.log(xyz);创建数组。

&#13;
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
ID Amount
1  *Blank*
1  10
2  20
3  30
&#13;
&#13;
&#13;

资源

答案 1 :(得分:0)

您需要检查数组是否已包含项目。如果没有,只需创建一个。您可能不需要在开头声明任何其他变量。

var xyz = [];

for (var i = 0; i < 5; i++) {
    // do this if you are not changing the objects a getting to this point a second time
    xyz[i] = {tx: 5};
}
alert(xyz);

查看实际操作:https://jsfiddle.net/mtr6hdty/2/

根据您在for循环中的操作,您还可以使用Ele中的简写版

相关问题