我有动态变量,如:
var4 = 56
var7 = 23
var32 = 53
...
var645 = 21
如何在JavaScript中循环使用这些内容,以便将这些值推送到数组vars
中?
答案 0 :(得分:0)
检查此pen
var var4 = 56;
var var7 = 23;
var var32 = 53;
//...
var var645 = 21;
var arr = [];
var currentScope = window;
//currentScope = parent.frames[2].window.location;
for( var key in currentScope )
{
console.log(key);
if (key.indexOf( "var" ) == 0 )
{
console.log( "RELEVANT " + key );
var suffix = parseInt( key.split( "var" ).join( "" ) );
if ( !isNaN( suffix ) )
{
arr.push( suffix );
}
}
}
console.log( arr );
答案 1 :(得分:0)
你可以这样做,但你必须知道第一个和最后一个"索引"以变量的名义" var"
var var0 = 0;
var var1 = 10;
var var2 = 20;
// var var3 = 30; // <--- this not exist !
var var4 = 40;
var vars = new Array();
for (var i=0; i<5; i++) {
try {
vars.push(eval("var" + i));
} catch(ex) { }
}