Javascript根据其名称创建变量 [英] Javascript create variable from its name

查看:57
本文介绍了Javascript根据其名称创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我们可以这样做:

In PHP we can do this:

$variable = "name_of_variable";
$this->{$variable} = "somevalue";

如何在javascript中做到这一点?

how to do this in javascript?

用例应为:

function Apple(){
    var name = "variable_name";
    this.(name) = "value";
}
console.log(new Apple());

输出

[Apple: {variable_name:"value"}]

推荐答案

尝试:

this[name] = "value";

所有对象都可以使用点和数组符号进行变量访问.

All objects can use dot and array notation for variable access.

还请注意,这将允许您通过点表示法创建不可访问的名称/值对:

Also note, this will allow you to create name value pairs that are inaccessible via dot notation:

var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine

如果要创建新的对象文字,则可以使用字符串文字作为具有特殊字符的值的名称:

If you are creating a new object literal, you can use string literals for the names for values with special characters:

var foo  = {'bar-baz':'fizzbuzz'};

但是您将无法在对象文字中将变量用作key,因为它们被解释为要使用的名称:

But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:

var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'

由于其他回答者都提到了eval,因此我将说明eval可能有用的情况.

Because other answerers are mentioning eval, I will explain a case where eval could be useful.

如果您需要使用具有动态名称的变量,而该变量在另一个对象上不存在.

If you need to use a variable with a dynamic name, and that variable does not exist on another object.

重要的是要知道,在全局上下文中调用var foo会将新变量附加到全局对象(通常是window).但是,在闭包中,由var foo创建的变量仅存在于闭包的上下文中,并且未附加到任何特定对象.

It's important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.

如果需要在闭包内使用动态变量名,则最好使用容器对象:

If you need a dynamic variable name within a closure it is better to use a container object:

var container = {};
container[foo] = 'bar';

总而言之,如果需要动态变量名称​​ 并且不能使用容器对象,则可以使用eval创建/访问/修改动态变量名称.

So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.

var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );

这篇关于Javascript根据其名称创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆