评估 ES6 数组理解字符串

Evaluate ES6 Array Comprehension String

本文关键字:字符串 数组 ES6 评估      更新时间:2023-09-26

在 ES6 中,我可以使用

[for(i1 of [0, 1]) for(i2 of [0, 1]) [i1, i2]]

并得到

[[0, 0], [1, 0], [0, 1], [1, 1]]



我可以构建一个字符串,例如

str = '[for(i0 of [0, 1]) for(i1 of [0, 1]) [i0, i1]]'

str = '[for(i1 of [0, 1]) for(i2 of [0, 1]) for(i3 of [0, 1]) [i1, i2, i3]]'.

如何评估/执行这样的字符串?

你可以做与在 ECMAScript 5 中相同的操作。使用任一eval

var arr = eval(str);

new Function

var arr = new Function('return' + str)();

使用 System.moduleSystem.define

从 http://www.2ality.com/2014/09/es6-modules-final.html:

  • System.module(source, options?)评估源代码中的 JavaScript 代码到模块(通过 promise 异步交付)。

  • System.set(name, module)用于注册模块(例如,通过System.module()创建的模块)。

  • System.define(name, source, options?)既计算源代码中的模块代码,又注册结果。