晴明的博客园 GitHub      CodePen      CodeWars     

[js] 错误接口数据处理

变量未声明,不存在。

        if (typeof value != 'undefined') {

        }

        if (typeof value == 'object') {

        }

变量已声明但未赋值,读取该变量(对象)某一属性

        let value;
        if ((value || {}).property) {

        }

判断数组

let value = [];

Array.isArray(value) //true

Object.prototype.toString.call(value) == '[object Array]' //true

//不推荐
value instanceof Array //true

空数组

        let value = [];

        if (value && value.length > 0) {
            console.log('pass')
        }

        value.forEach((v) => {
            console.log(v)
        })

判断对象

let value = {};

Object.prototype.toString.call(value) == '[object Object]' //true

//需要注意array也是object
typeof value == 'object' //true

//不推荐
Object.prototype.isPrototypeOf(value) //true

判断 空对象

        let value = {};

         //es5
        if (typeof value == 'object' && Object.getOwnPropertyNames(value).length > 0) {
            console.log('pass')
        }
        
        //es6
        if (typeof value == 'object' && Object.keys(value).length > 0) {
            console.log('pass')
        }

        if (typeof value == 'object' && !isEmpty(value)) {
            console.log('pass')
        }

        //不推荐
        if (typeof value == 'object' && JSON.stringify(value) != '{}') {
            console.log('pass')
        }


        function isEmpty(obj) {
            //能用于判断是否为空字符串、对象、数组
            for (let i in obj) {
                return false;
            }
            return true;
        }

数值计算

数字可能是number或是string

        let a = '100';
        let b = 100;
        let c = a + b;//"100100"
        c = Number(a) + b;//200

string里可能不是数字,而且结果预期为整数

        let a = 'xx';
        let b = 100;
        c = (a | 0) + b;//100

可能是任意类型时

        let a = 'xx';
        let b = '1';
        let c = 10;
        let d = [];
        let e = {};
        let count;
        count = convertNumber(a) + convertNumber(b) + convertNumber(c) + convertNumber(d) + convertNumber(e);//11

        function convertNumber(num) {
            let result = Number(num);
            if (isNaN(result)) {
                return 0
            }
            return result;
        }

默认值

        let a;
        let b = a || 'xx';//'xx'

        function test(x = 'x', y = 'y') {
            console.log(x)//x
            console.log(y)//y
            var x = 'xxx';
            console.log(x)//'xxx'
            //let x = 'zzz';//error
        }
posted @ 2017-07-28 17:40  晴明桑  阅读(287)  评论(0编辑  收藏  举报