简体   繁体   English

Javascript:可以将字符串强制转换为类型常量/将其转换为类型常量吗?

[英]Javascript: Can a string be cast as/converted to a type constant?

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: 在Javascript中这样:

var ts = "Array";
var magic_type = ????; //magic
var obj_instance = new magic_type;

is valid and obj_instance == [] ? 有效且obj_instance == []吗?

You can instantiate it by using bracket notation with the global object. 您可以通过对全局对象使用括号符号来实例化它。

var arr = new window['Array'];

jsFiddle . jsFiddle

If the constructor takes arguments, add them to the end. 如果构造函数接受参数,请将其添加到末尾。

As a side note, your code example... 附带一提,您的代码示例...

obj_instance === []

...won't ever evaluate to true because the [] syntax will create a new Array with a different memory location. ...永远都不会评估为true因为[]语法会创建一个具有不同内存位置的新Array

var instance = new window[someString]();

不需要魔术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM