简体   繁体   中英

Iterating over variables in Javascript

My goal with block 2 is to streamline my existing block 1 code by defining javascript variables in a for loop.The code below is giving me the error "Unexpected token [" in the console. I am not sure I am using the proper syntax here. Is there a way to loop over an array and insert each dynamically to get the desired result of block 1?

I am able to console.log details_object[i] in block 2 and successfully see all the array elements but that is about as far as I can get.

   /*Block 1*/

   /*var title = document.getElementById('title').value;
   var phone = document.getElementById('phone').value;
   var firstn = document.getElementById('firstn').value;
   var lastn = document.getElementById('lastn').value;
   var displayn = document.getElementById('displayn').value;*/

   /*Block 2 less code!*/

   var details_object = ["title", "phone", "firstn", "lastn", "displayn"];

   for(var i=0, l = details_object.length; i < l; i++){
     var details_object[i] = document.getElementById("'"+details_object[i]+"'").value;
   }
var details_object[i] = document.getElementById("'"+details_object[i]+"'").value;
 ^---// Delete this var

That is what was causing the error. You probably want something like this:

var details_object = ["title", "phone", "firstn", "lastn", "displayn"];
var obj = {};

for(var i=0, l = details_object.length; i < l; i++){
  obj[details_object[i]] = document.getElementById(details_object[i]).value;
}

Now access obj.title , obj.phone , etc.

Try

var scope = this;
for(var i=0, l = details_object.length; i < l; i++){
     scope[details_object[i]] = document.getElementById(details_object[i]).value;
}

this will create a variable named with the name stored in details_object[i] into the current scope. Hopefully you are not doing this on the global scope as this will pollute it.

Try this

var details_object = ["title", "phone", "firstn", "lastn", "displayn"];
for(var i=0, l = details_object.length; i < l; i++){
     window[details_object[i]] = document.getElementById("'"+details_object[i]+"'").value;
   }

My goal with block 2 is to streamline my existing block 1 code by defining javascript variables in a for loop

You can only do that with eval or with properties of the global object (which is the window object in a browser). Javascript does not allow access to a local variable object, so you can't directly address its properties. You can only access them using an identifier name that is first resolved in the current execution context (more or less on a local variable object) and then on the scope chain which has the variables of outer execution contexts if there are any.

The exception is that global variables are made properties of the global object. These can be created and accessed using square bracket notation, however global properties created through assignment have subtle differences to those created using declarations (eg declared global variables can't be deleted, properties created through assignment can).

So if you are happy to create proerties of the global object, you can do:

// In global code
var global = this;

// Anywhere you wish to create, read or assign to a global property
global[whatever] ...   // using an identifier whose value resolves to a string
global['whatever'] ... // using a string
global[foo()] ...      // using some other type of expression that returns a string

However, it is considered far better practice to create a single object for such properties so as to avoid the possiblity of naming conflicts with properties of the global object, eg

var myVars = {}

myVars[varName]  = varValue;

Otherwise, you can use eval to create local variables in function code:

eval('var ' + whatever + ' = 3');
alert(whatever); // 3

However, that is not recommended. It is preferred to use a myVars object that is shared either through a closure, inheritance or as a global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM