我使用变量count渲染for循环。请查看此示例
我有5个这样的变量:
var reactionWeightage5 = 30;
var reactionWeightage4 = 06;
var reactionWeightage3 = 70;
var reactionWeightage2 = 80;
var reactionWeightage1 = 10;
我需要像这样渲染
for (var i = 1; i <= 5; i++) {
var test = reactionWeightage[i];
etc .....
}
我收到以下错误:
“reactionWeightage未定义”
有人可以为此提供帮助吗?
答案 0 :(得分:3)
最简单的方法就是像这样创建数组:
var reactionWeightage = [30, 06, 70, 80, 10];
迭代
for (var i = 0; i < reactionWeightage.length; i++) {
console.log(reactionWeightage[i]);
}
答案 1 :(得分:1)
reactionWeight不是数组。如果使用[]运算符,则需要使用数组。
尝试创建这样的内容:
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
然后您可以像这样访问它:
alert(mycars[2]); //will alert BMW
答案 2 :(得分:1)
不使用五个变量,而是使用例如字典/对象:
var reactionWeightage = {
5: 30,
4: 06,
3: 70,
2: 80,
1: 10
};
for (var i = 1; i <= 5; i++) {
var test = reactionWeightage[i];
etc .....
}
然而,完全回答这个问题是一个如何实现你想要的例子(仅用于学术目的,不要在实际代码中使用):
for (var i = 1; i <= 5; i++) {
var test = eval('reactionWeightage'+i);
etc .....
}
答案 3 :(得分:0)
您需要将reactionWeightage定义为数组,而不是声明5个单独的变量。最小化你已经拥有的东西:
var reactionWeightage = new Array();
reactionWeightage[5] = 30;
reactionWeightage[4] = 06;
reactionWeightage[3] = 70;
reactionWeightage[2] = 80;
reactionWeightage[1] = 10;