jQuery.parseJSON 和 JSON.parse 两个执行相同任务的函数。如果已加载jQuery库,则使用 jQuery.parseJSON 比使用 JSON.parse 更好性能?
jQuery.parseJSON and JSON.parse are two functions that perform the same task. If the jQuery library is already loaded, would using jQuery.parseJSON be better than using JSON.parse, in terms of performance?
如果是,为什么?如果不是,为什么不呢?
If yes, why? If no, why not?
推荐答案这是摘录来自jQuery 1.9.1 :
parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from json/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); },如你所见,jQuery将使用原生 JSON.parse 方法(如果可用),否则它将尝试使用 new Function 评估数据,这有点像 eval 。
As you can see, jQuery will use the native JSON.parse method if it is available, and otherwise it will try to evaluate the data with new Function, which is kind of like eval.
所以是的,你一定要使用 jQuery.parseJSON 。
So yes, you should definitely use jQuery.parseJSON.
更多推荐
jQuery.parseJSON vs JSON.parse
发布评论