javascript eval方法语法

javascript eval method syntax

本文关键字:语法 方法 eval javascript      更新时间:2023-09-26

我在web应用程序中使用jquery。在那里我们使用下面的eval方法。

    var json = eval('(' + data + ')');

经过谷歌搜索,我发现上面使用的eval方法将json数据转换为javascript对象。但这种语法意味着什么?为什么必须将它括在('(')')括号内。请帮我理解。

使用()来封装数据是为了防止{}被解析为块。

var json = eval('{}');  // the result is undefined
var json = eval('({})');  // the result is the empty object. 
var json = eval('{"a": 1}'); // syntax error
var json = eval('({"a": 1})'); // the result is object: {a: 1}

但是您不应该使用eval来解析json数据。

请改用var json = JSON.parse(data);或某些库函数。

不要使用eval来解析json。由于您使用的是jQuery,请使用$.parseJSON(data)。如果数据包含window.close()怎么办?

WRT到括号,你可以在douglas crackford的json2.js:中看到一条解释它们的评论

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.