规避评估

Circumventing eval

我在 table 中列出了代码,我想访问某个单元格中的代码并 运行 它。问题是 table 中的所有值都是字符串,我无法将字符串转换为代码。

function readTable(tableName, rowId, columnName) {
 readRecords(tableName, {}, function(records) {
   for (var i =0; i < records.length; i++) {
    var record = records[i];
      if (record.id === rowId) {
      if (record[columnName]!==undefined) {
          eval(record[columnName]);
      }
      }
   }
 }); 
}

有什么办法绕过使用 eval 吗?例如,我的一个 table 单元格中的文本被解释为(在保存 table 之后)

"setText(\"specialbutton\",\"You got tricked. Be careful next time.\");gameovercounter()"

它 运行 是

setText("specialbutton","You got tricked. Be careful next time.");gameovercounter()

使用评估后。在这种情况下,我还没有想出如何避免 eval。

避免 eval 和文本中的 运行 代码的最佳方法是使用:

new Function(strFuncBody)

将您的评估代码替换为:

if (record[columnName]!==undefined) {
    // create a function to run
    var func = new Function(record[columnName]);
    // then call the function...
    func();
}

eval() 和 Function() 之间存在很大差异,在本文的 "Do not ever use eval!" 部分进行了解释:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

无论如何,如果您不能完全控制字符串包含的内容,则永远不要 运行 将字符串作为代码使用 new Function() 或 eval()。