admin管理员组

文章数量:1427065

Imagine i had: <div id names>142,140,150</names>

could i then (in Javascript) write a forloop which declares variable names, with these values appended ie

var list = document.getElementById('names').innerHTML.Split(',');

for(i=0; i<list.Length; i++){
    var 'beginning' + list[i];
}

so i'd essentially want to create:

var beginning142
var beginning140
var beginning150

Imagine i had: <div id names>142,140,150</names>

could i then (in Javascript) write a forloop which declares variable names, with these values appended ie

var list = document.getElementById('names').innerHTML.Split(',');

for(i=0; i<list.Length; i++){
    var 'beginning' + list[i];
}

so i'd essentially want to create:

var beginning142
var beginning140
var beginning150
Share Improve this question edited Jul 1, 2010 at 9:47 Oded 499k102 gold badges893 silver badges1k bronze badges asked Jul 1, 2010 at 9:45 JohnJohn 1011 silver badge3 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 7

You can indeed:

window['beginning' + list[i]] = 'value';

Funny coincidence, I answered a very closely related question 10 seconds prior to this one, and then I used exactly this as an example. So a more elaborate explanation on why this works is available here.

You can do something like this:

for(var i = 0; i<100; i++)
{
   eval("var beginning"+i);
}

For developers afraid from eval This is one of good articles talking about eval and how it is not an evil: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/

I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.

I can't add comment to your question due to low reputation score - this is not answer but advice. I think It would be better to create single array with your keys 142,140,150...

Why don't you define an object that has those values as an attribute on it.

For example:

var myVariable = function(id, value){
 this.Id = id;
 this.Value = value;
};

then you can just instantiate this object. I think it is less complicated and more readable in the end.

本文标签: JavascriptHTMLis it possible to create variable names from a loopStack Overflow