Javascript:字符串可以转换为类型常量吗?
如果我有一个包含字符串的变量,有没有办法可以将该字符串的内容视为类型的名称?
例如,Javascript 中是否存在 ???
这样:
var ts = "Array";
var magic_type = ????; //magic
var obj_instance = new magic_type;
有效且 obj_instance == []
?
If I have a variable containing a string, is there a way that I can treat the contents of that string as the name of a type?
For example, is there a ????
in Javascript such that:
var ts = "Array";
var magic_type = ????; //magic
var obj_instance = new magic_type;
is valid and obj_instance == []
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过对全局对象使用括号表示法来实例化它。
jsFiddle。
如果构造函数接受参数,请将它们添加到末尾。
作为旁注,您的代码示例...
...永远不会计算为
true
因为[]
语法将创建一个新的Array 具有不同的内存位置。
You can instantiate it by using bracket notation with the global object.
jsFiddle.
If the constructor takes arguments, add them to the end.
As a side note, your code example...
...won't ever evaluate to
true
because the[]
syntax will create a newArray
with a different memory location.不需要魔法。
No magic required.