I have dynamic variables like:
var4 = 56
var7 = 23
var32 = 53
...
var645 = 21
How can I loop through these in JavaScript so I can push each of these values in an array vars?
-
depends on what scope the variables are in ?adeneo– adeneo2016年01月06日 13:30:53 +00:00Commented Jan 6, 2016 at 13:30
-
They are in global namespace windowGogo– Gogo2016年01月06日 13:31:27 +00:00Commented Jan 6, 2016 at 13:31
-
I'd suggest to start with an array in the first place if possible.Felix Kling– Felix Kling2016年01月06日 13:32:38 +00:00Commented Jan 6, 2016 at 13:32
2 Answers 2
You can do that but you must know the first and the last "index" in the name of variables "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) { }
}
answered Jan 6, 2016 at 13:43
Baro
5,5932 gold badges21 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
check this 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 );
answered Jan 6, 2016 at 13:39
gurvinder372
68.6k11 gold badges78 silver badges98 bronze badges
Comments
lang-js