【问题标题】:Evaluate ES6 Array Comprehension String评估 ES6 数组理解字符串
【发布时间】:2014-12-11 06:43:17
【问题描述】:

在 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]]'.

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

【问题讨论】:

  • 与在 ES5 中评估的方式相同:eval, new Function..
  • 您或许可以使用Traceur.compile API。

标签: javascript arrays eval list-comprehension ecmascript-6


【解决方案1】:

您可以执行与 ECMAScript 5 中相同的操作。使用 eval:

var arr = eval(str);

new Function:

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

【讨论】:

  • 感谢以上。我应该指定我的工作环境——我正在使用 grunt-traceur-simple 将 es6 转换为 es5。对于以下代码,转译器什么都不做: var str = '[for (i of [0,1]) i]'; var arr = eval(str);我在浏览器中收到了“SyntaxError: Unexpected token for”。我该如何解决这个问题?
【解决方案2】:

使用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?) 计算源代码中的模块代码并注册结果。

【讨论】:

  • 感谢您的回答。但我不知道如何在我的情况下使用它。我把我的代码放在Traceur Repl 中。如何使用 traceur 评估数组理解字符串?
猜你喜欢
  • 2013-09-01
  • 1970-01-01
  • 2022-01-25
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多