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 beginning150Share 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
4 Answers
Reset to default 7You 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
版权声明:本文标题:JavascriptHTML, is it possible to create variable names from a loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738679950a2106491.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论