0

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?

3
  • depends on what scope the variables are in ? Commented Jan 6, 2016 at 13:30
  • They are in global namespace window Commented Jan 6, 2016 at 13:31
  • I'd suggest to start with an array in the first place if possible. Commented Jan 6, 2016 at 13:32

2 Answers 2

1

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) { }
}

This is the JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.