最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

constructing javascript variable names at runtime - Stack Overflow

programmeradmin5浏览0评论
someFunction(link) {
  someOtherFunction('div' + link);
}

By calling someFunction("Test"), the string "divTest" gets passed to someOtherFunction(). But I want the value of the variable "divTest" to be passed.

How can that be done?

someFunction(link) {
  someOtherFunction('div' + link);
}

By calling someFunction("Test"), the string "divTest" gets passed to someOtherFunction(). But I want the value of the variable "divTest" to be passed.

How can that be done?

Share Improve this question asked Feb 22, 2009 at 23:21 ryonliferyonlife 6,62314 gold badges54 silver badges65 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 10

Make your variables members of an object. Then you can use [] to access the objects members using a string:

var byname = {
  divabc: ...,
  divxyz: ...
};

function someFunction(link) {
  someOtherFunction(byname['div'+link]);
}

someFunction('abc'); // calls someOtherFunction(byname.divabc)

For this kind of dynamic construction/access of variable names you should use the alternative object notation where:

object.member === object["member"]

This way you could construct your variable name as a string and use it inside square brackets for accessing object members.

eval will do this, but it's usually indicative of some other problem with the program when you want to synthesize identifiers like this. As Ionut says it's better to use the [] notation. I like to link to this whenever questions like this come up.

You should be able to accomplish this with the 'eval' function.

Try this:

var divFoo = "bar";
function someFunction(link) {
    someOtherFunction(this['div' + link]);
}
function someOtherFunction(value) {
    alert(value);
}
someFunction("Foo");

As wybiral said, all you need is eval:

someFunction(link) {
  someOtherFunction(eval('(div' + link + ')');
}

Basically what it does is evaluates the contents of a string as code. Obviously eval is a dangerous little tool since it allows executing arbitrary code so take care when using it.

发布评论

评论列表(0)

  1. 暂无评论