如何在没有eval的情况下在运行时组装Javascript中的var?
var lc = $('.bezeichnung-1').length;
for (var lt = 1; lt <= lc; lt++) {
eval("var neuerwert"+lt+"=0;"); // this works but I don't want to use it because I read that eval is bad
}
var lc = $('.bezeichnung-1').length;
for (var lt = 1; lt <= lc; lt++) {
window["var neuerwert"+lt] = 0; // this does not work
}
Run Code Online (Sandbox Code Playgroud)
如何在没有eval的情况下在运行时组装Javascript中的var?
你没有,但你可以使它成为某种东西的属性.
如果这些已经在全球范围内,它们已经是属性:
var lc = $('.bezeichnung-1').length;
for (var lt = 1; lt <= lc; lt++) {
window["neuerwert"+lt] = 0;
// -----^ no `var` keyword
}
Run Code Online (Sandbox Code Playgroud)
如果它们不在全球范围内(对你有用!),请将它们作为对象的属性,例如:
var neuerwert = {
1: /*...value here...*/,
2: /*....value here...*/
};
Run Code Online (Sandbox Code Playgroud)
或数组
var neuerwert = [
/*...value here...*/,
/*....value here...*/
];
Run Code Online (Sandbox Code Playgroud)
然后
var lc = $('.bezeichnung-1').length;
for (var lt = 1; lt <= lc; lt++) {
neuerwert[lt] = 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,数组索引从...开始0,因此lt如果您正在使用数组,则可能需要进行调整.