Javascript:字符串可以转换为类型常量吗?

发布于 2025-01-03 20:15:34 字数 250 浏览 2 评论 0原文

如果我有一个包含字符串的变量,有没有办法可以将该字符串的内容视为类型的名称?

例如,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与君绝 2025-01-10 20:15:34

您可以通过对全局对象使用括号表示法来实例化它。

var arr = new window['Array'];

jsFiddle

如果构造函数接受参数,请将它们添加到末尾。

作为旁注,您的代码示例...

obj_instance === []

...永远不会计算为 true 因为 [] 语法将创建一个新的 Array 具有不同的内存位置。

You can instantiate it by using bracket notation with the global object.

var arr = new window['Array'];

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.

旧城烟雨 2025-01-10 20:15:34
var instance = new window[someString]();

不需要魔法。

var instance = new window[someString]();

No magic required.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文