获取数据守卫:为解决取值链长导致数据不可信问题

为解决问题:key链太长,导致数据获取不可行问题

例如:

 let res = {
            data: {
                config: {
                    // form_config:{
                    //     list:[{name:'hww'},{}],
                    //     form:{}
                    // }
                }
            }
        },
       获取最内层list的长度
 
         之前的写法:
 
               let len = res.data.config.form_config.list.length
 
         问题:不知道哪个值会抛出undefined或者null,就会导致程序出问题
 
     用函数守卫获取:
  
    let len = $catch(res, 'data.config.form_config.list.length',0)
   
   获取到了就返回获取值,未获取到返回默认值0,这样就能保证数据不对的情况下程序正常运行。
 
/**
 *
 *
 * @param {*} data 取值目标,需为对象
 * @param {*} keyStr 取值key链(例:form_config.list.0.name),数组取值同样用点
 * @param {string} [def=''] 取值出错时返回的默认值,不传默认为字符串
 * @returns
 */
function $catch(data, keyStr, def = '') {

    const debug = true // 要不要错误输出

    const type = function (p) {
        return Object.prototype.toString.call(p).slice(8, -1)
    }

    if (typeof data !== 'object'||data===null) {

        debug && console.error(`%c error message from $catch %c : data export Object/Array ,but got ${type(data)}`, 'color:orange',
            '');

        return def
    }

    if (type(keyStr) !== 'String') {

        debug && console.error(`%c error message from $catch %c : key export string ,but got ${type(keyStr)}`,
            'color:orange', '');

        return def
    }

    if (keyStr === '') {

        debug && console.error(`%c error message from $catch %c : key chain is empty !`, 'color:orange', '');

        return def
    }

    let keyArr = keyStr.split('.')
    let _data = data
    let _index = 0

    for (let index = 0; index < keyArr.length; index++) {
        _data = _data[keyArr[index]]
        _index = index
        if (typeof _data === 'object'&&_data!==null) {
            debug && console.error(`%c error message from $catch %c ${keyArr.slice(0,_index+1).join('.')} 为 "undefined" !`,
                'color:orange', '');
            break;
        }

    }

    return _data || def
}

 

posted @ 2020-07-31 18:22  superjsman  阅读(192)  评论(0编辑  收藏  举报