在PHP中,你可以做这样惊人/可怕的事情:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
有什么方法可以用Javascript做这样的事情吗?
例如,如果我有一个var name = '变量的名称';我可以得到一个引用的变量与名称?
在PHP中,你可以做这样惊人/可怕的事情:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
有什么方法可以用Javascript做这样的事情吗?
例如,如果我有一个var name = '变量的名称';我可以得到一个引用的变量与名称?
当前回答
对于那些需要导出动态命名变量的人来说,这是一种替代方法
export {
[someVariable]: 'some value',
[anotherVariable]: 'another value',
}
// then.... import from another file like this:
import * as vars from './some-file'
另一种方法是简单地创建一个对象,其键是动态命名的
const vars = { [someVariable]: 1, [otherVariable]: 2 };
// consume it like this
vars[someVariable];
其他回答
他们的意思是不,你不能。 没有办法完成它。 所以你可以这样做
function create(obj, const){
// where obj is an object and const is a variable name
function const () {}
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
}
有一个创建函数,就像在ECMAScript 5中实现的那样。
虽然这有一个公认的答案,但我想补充一个观察:
在ES6中使用let无效:
/*这不是工作*/ let t = "skyBlue", M = "黄金", B = "番茄"; Let color = window["b"]; console.log(颜色);
但是使用var是可行的
/*这个正在工作*/ var t = "skyBlue", M = "黄金", B = "番茄"; Let color = window["b"]; console.log(颜色);
我希望这对一些人有用。
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
试试这个…
这将做你在php中所做的事情:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
如果你不想使用像window或global (node)这样的全局对象,你可以尝试这样做:
var obj = {};
obj['whatever'] = 'There\'s no need to store even more stuff in a global object.';
console.log(obj['whatever']);