nav*_*een 5 javascript jquery parsing json
function (data) {
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim(data);
// Attempt to parse using the native JSON parser first
if (window.JSON && window.JSON.parse) {
return window.JSON.parse(data);
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {
return (new Function("return " + data))();
}
jQuery.error("Invalid JSON: " + data);
}
Run Code Online (Sandbox Code Playgroud)
我无法理解以下后备
return (new Function("return " + data))();
Run Code Online (Sandbox Code Playgroud)
而且(这个不是在jQuery中)
return (eval('('+ data + ')')
Run Code Online (Sandbox Code Playgroud)
我想知道这些事情
new Function())new Function()允许您将函数作为字符串传递。
在本例中,创建该函数只是为了返回 json 字符串描述的对象。由于 json 是有效的对象文字,因此该函数仅返回 json 中定义的对象。新函数会立即被调用,并返回该对象。
就性能而言,一些快速谷歌搜索发现声称new Function()比 更快eval,尽管我自己还没有测试过。
| 归档时间: |
|
| 查看次数: |
537 次 |
| 最近记录: |