zoukankan      html  css  js  c++  java
  • JavaScript中JSON的处理心得

    一门语言用到深处,就避免不了要对数据的类型进行准确判断,并针对其类型做正确处理。

    抛开在Web前端环境不谈,从一门独立编程语言的角度来看js,你就会感受到对js中数据类型的理解有多么重要。

    1. 禁止直接多级访问对象属性,必须一级一级访问;如abc.d这样是不会造成报错的,但abc.d.e可能会造成异常
    2. 在继续往里面访问时,先用一个类型分析函数分析一下

    例如:

    /**
     * 判断给定对象的类型,返回字符串格式的名称
     * @param {Object} obj
     * @returns {String}
     */
    var parseType = function (obj) {
        var type = typeof obj;
        if ("object" === type) {
            if (obj) {
                if (obj instanceof Array) {
                    return "array";
                }
                if (obj instanceof Object) {
                    return type;
                }
                var native_obj = Object.prototype.toString.call(obj);
                if ("[object Window]" === native_obj) {
                    return "object";
                }
                if ("[object Array]" === native_obj || "number" === typeof obj.length && "undefined" !== typeof obj.splice && "undefined" !== typeof obj.propertyIsEnumerable && !obj.propertyIsEnumerable("splice")) {
                    return "array";
                }
                if ("[object Function]" === native_obj || "undefined" !== typeof obj.call && "undefined" !== typeof obj.propertyIsEnumerable && !obj.propertyIsEnumerable("call")) {
                    return "function";
                }
            } else {
                return "null";
            }
        } else if ("function" === type && "undefined" === typeof obj.call) {
            return "object";
        }
        return type;
    };
    
    //示例
    
    var abc = {};
    console.log(parseType(abc.type));
    console.log(parseType(abc.type.native_obj));
    

    在nodejs环境执行:

    undefined
    /Users/jixxxxxx/Web/js/type_ha.js:32
    console.log(parseType(abc.type.native_obj));
                                  ^
    
    TypeError: Cannot read property 'native_obj' of undefined
        at Object.<anonymous> (/Users/jixxxxxx/Web/js/type_ha.js:32:31)
        at Module._compile (module.js:425:26)
        at Object.Module._extensions..js (module.js:432:10)
        at Module.load (module.js:356:32)
        at Function.Module._load (module.js:313:12)
        at Function.Module.runMain (module.js:457:10)
        at startup (node.js:138:18)
        at node.js:974:3
    
    
  • 相关阅读:
    CWinApp::OnIdle 的使用方法
    C++标准模板库
    MFC日期字符串转换
    mfc 中隐藏文件的操作
    VS2010 中修改项目名称
    C# 与C++ 数组传参数区别
    C++中使用clr(通用语言库) 及相关问题
    AutoCAD 2012(64位)安装及下载地址
    0xC015000F EEFileLoadException
    Linux安装MySQL,简化的
  • 原文地址:https://www.cnblogs.com/x3d/p/js-json-access.html
Copyright © 2011-2022 走看看