1

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;
   }
1
  • you dont need the "'" parts in the function call, each of the array elements are already strings. Commented Jan 24, 2014 at 1:49

4 Answers 4

1
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.

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

2 Comments

The OP isn't trying to redeclare the array elements, he is trying to declare new variables based on the names in the array.
This actually did the trick. I am passing the results of these variables into a url. Once I utilized the above code I was able to pass each one into var obj={} and access them via obj. as Matt suggested - thanks for the help with this!
1

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.

4 Comments

@BlackSheep but that wouldn't answer the actual question. And +1 to Patrick Evans for beating me to the same answer.
I would normally as well, but didnt know if he was wanting to have the variables available directly from the scope or not.
Awesome! Thanks guys. In terms of global scope I have this in a function so shouldn't have to worry about scope conflicts. @BlackSheep are you referring to putting all this in a Javascript object? Just checking :-)
-1 this has nothing to do with scope, it is set entirely by the call (or bind) and may be a different object (or not an object at all in strict mode) on each call. The above code will add properties to some random object (probably the global object in this case) and is no better (probably worse) than using window['identifier'] in a browser.
0

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

2 Comments

This would probably suffice in most cases, but doesn't account for localized scope.
it also would pollute the window object, which you should try not to do.
0

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 (e.g. 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, e.g.

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.

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.