代码之家  ›  专栏  ›  技术社区  ›  Alessandro Pace

Angular4-检查嵌套对象项是否为空

  •  4
  • Alessandro Pace  · 技术社区  · 7 年前

    我正在检查名为“token”的嵌套对象项在带有Angular4的AngularIDE中是否为空

    if (typeof this.user.data.token !== "undefined")
    

    <Cannot read property 'token' of null>

    我是否需要检查每个嵌套对象是否存在?

    3 回复  |  直到 7 年前
        1
  •  4
  •   Faly    7 年前

    if (this.user && this.user.data && this.user.data.token) {
    }
    
        2
  •  1
  •   Alejandro Camba    7 年前

    永远记住 未定义 这意味着声明了一个变量,但其中没有值,并且 是实际赋值。未定义的是类型,null是对象。所以

     if(!(this.user.data.token == null)); 
    

    || 然后键入下一个条件。

    this.user.data.token != undefined && ... 
    

        3
  •  0
  •   abhijeetwebdev    6 年前

    /**
    * @param obj: to check the nested key
    * @param args: array of location to the nested key to check ['parentNode', 'childNode', 'grandChildNode']
    */
    checkNestedKey(obj, args) {
        for (let i = 0; i < args.length; i++) {
            if (!obj || !obj.hasOwnProperty(args[i])) {
                return false;
            }
            obj = obj[args[i]];
        }
        return true;
    }
    
    // to check if value exist this.user.data.token
    if (this.checkNestedKey(this.user, ['data', 'token'])) {
        // continue here
    }