开发者

Can you set a variable name equal to another variable's value?

开发者 https://www.devze.com 2023-01-25 20:58 出处:网络
I am interested in knowing if its even possible. One example is the variable already exists. foo = 1; var bar = \'foo\';

I am interested in knowing if its even possible.

One example is the variable already exists.

foo = 1;
var bar = 'foo';

if('foo' == 1)?  

Is there a way to do that.

Is there a way to say something like开发者_StackOverflow社区 bar == foo.variablename


Yes you can but I wouldn't recommend it.

s="unicorn"
eval("var " + s + " = 'test'")
alert(unicorn)

but from the text in your question it kind of sounds like you want to check if a variable exists and that is also possible

if (typeof variable == "undefined") alert("It's not defined!");


No to variables, Yes to properties. Since variables are properties:

javascript:var foo='bar';this[foo]='baz';alert(bar)


I think, I didn't get what's your concrete purpose, but with function eval you should be able to perform the desired operation.

0

精彩评论

暂无评论...
验证码 换一张
取 消