• 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
    
    
  • 相关阅读:
    Mybatis学习-ResultMap
    MySql模糊查询 concat()函数
    Spring学习-依赖注入
    Struts2学习-struts执行过程简述
    Struts2学习-jsp中超链接传参问题
    Struts2学习-struts.xml文件配置
    第四次作业
    第三次作业
    Django -Ajax
    Django -ORM
  • 原文地址:https://www.cnblogs.com/x3d/p/js-json-access.html
Copyright © 2020-2023  润新知