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?

如果是,为什么?如果没有,为什么不呢?

推荐答案

以下是一段摘录from 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 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 );
},

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.

So yes, you should definitely use jQuery.parseJSON.

Jquery相关问答推荐

用 jQuery/JavaScript 检测数字或字母?

如何在 bootstrap 模式关闭并重新打开时重置 bootstrap 模式?

如何制作 AngularJS 指令来停止传播?

如何在使用 jQuery 单击特定链接时打开 bootstrap 导航选项卡的特定选项卡?

Ajax 更新后在 jQuery 中重新绑定事件(更新面板)

lodash debounce 在匿名函数中不起作用

jQuery中追加的相反

如何使用 jQuery 为文本对齐动态添加样式

为什么找不到我的 json 文件?

jquery:更改URL地址而不重定向?

如何阻止 Chrome 进入调试模式?

Jquery - 如何获取样式显示属性无/块

JQuery Ajax Post 导致 500 内部服务器错误

使用 Jquery 更改页面标题

如何检测是否安装了 Flash,如果没有,显示一个隐藏的 div 通知用户?

如何在 JQuery 中 Select 除单击元素之外的所有类?

jQuery - 从元素内部 Select 元素

由于滚动,响应表内的 bootstrap 按钮下拉菜单不可见

detach()、hide() 和 remove() 之间的区别 - jQuery

如何使用 jQuery 或仅使用 Javascript 将按钮重定向到另一个页面