一切都很顺利,但当我声明变量 answeredQ+i 时会出错。
var count = 5;
for(var i=0;i<count;i++){
var className = '.myclass'+i;
var answeredQ+i = $(className).map(function(){
return $(this).text();
}).get();
}
一切都很顺利,但当我声明变量 answeredQ+i 时会出错。
var count = 5;
for(var i=0;i<count;i++){
var className = '.myclass'+i;
var answeredQ+i = $(className).map(function(){
return $(this).text();
}).get();
}
var count = 5;
var answered = {};
for(var i=0;i<count;i++){
var className = '.myclass'+i;
answered['Q' + i] = $(className).map(function(){
return $(this).text();
}).get();
}
answered.Q1
或answered['Q1']
来访问第一个变量,使用Q2来访问第二个变量,以此类推。使用 window['answeredQ'+i]
,但是你最好将答案分配给一个数组,而不是直接分配给全局作用域。
var count = 5;
for (var i = 0; i < count; i++) {
var className = '.myclass' + i;
window['answeredQ' + i] = $(className).map(function() {
return $(this).text();
}).get();
}
window['answeredQ'+i]
会在全局作用域中创建变量,对吗? - ArunaansweredQ0
或window.answeredQ0
或window['answeredQ0']
。 - synthet1c由于此变量声明无效,您可以使用一个对象
来保存所有这些动态键,并在for
循环之外使用相同的对象,如下所示。
var count = 5;
var answers = {};
for(var i=0;i<count;i++){
var className = '.myclass'+i;
answers['answeredQ' + i] = $(className).map(function(){
return $(this).text();
}).get();
}
console.log(answers);
Object.keys(answers).forEach(function(key) {
console.log(key + ': ');
console.log(answers[key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
answeredQ1
,answeredQ2
,... 的变量? - Weedoze