简体   繁体   English

Javascript-typeof不适用于动态对象

[英]Javascript - typeof not working for dynamic object

When none of the following child objects have been created 没有创建以下子对象时

if(typeof this.obj[child1][child2]!=="undefined"){
}

The above does not work however this does 上面不起作用但是这样做

if(typeof this.obj[child1]!=="undefined"){
}

this is because the priority of typeof is lower than that of [] or . 这是因为typeof的优先级低于[]或的优先级. , so the [] is executed first and throws an error: ,因此[]首先执行,并引发错误:

> typeof foo == "undefined"
true
> typeof foo.bar == "undefined"
ReferenceError: foo is not defined

To check long chains of nested properties you can use a function like this: 要检查嵌套属性的长链,可以使用如下函数:

function hasKeys(obj, keys) {
    for(var i = 0; i < keys.length; i++) {
        if(typeof obj[keys[i]] == "undefined")
            return false;
        obj = obj[keys[i]];
    }
    return true;
}

if(hasKeys(this, ["obj", "child1", "child2"])) ...

or better, handle an exception: 或者更好,处理一个异常:

try {
    val = this.obj['foo']['bar']['baz'];
} catch(err) {
    // deal with undefined val
}

You don't really need the typeof ... 'undefined' to determine if this.obj[child1][child2] is not undefined . 您实际上并不需要typeof ... 'undefined'来确定this.obj[child1][child2]是否不是undefined Instead use: 而是使用:

if (this.obj && this.obj[child1] && this.obj[child1][child2]) {}

As in: 如:

var obj = {};
obj.c1 = {};
alert( obj && obj.c1 && obj.c1.c2 ? 'obj.c1.c2 exists' : 'nope'); 
     //=> "nope"
obj.c1.c2 = 1;
alert( obj && obj.c1 && obj.c1.c2 ? 'obj.c1.c2 exists' : 'nope'); 
     //=> "obj.c1.c2 exists"

You could create a function to determine the existence of a certain path in any Object : 您可以创建一个函数来确定任何Object是否存在某个路径:

function pathExists(root,path){
  var pathx = path.constructor === Array && path || path.split(/\./)
    , trial
    , pathok = true
  ;

  while (pathx.length && pathok) {
    trial = pathx.shift();
    pathok = (root = root && root[trial] || false, root);
  }
  return pathok;
}
// usage examples
var obj = {c1:1};
pathExists(obj,'c1.c2'); //=> false
pathExists(obj,'c1'); //=> 1
obj.c1 = { c2: {c3: 3} };
pathExists(obj,['c1','c2','c3']); //=> 3
// your case
if ( pathExists(this,[obj,child1,child2]) ) { /*...*/ }

use this for the first case - 在第一种情况下使用它-

if(this.obj[child1] && typeof this.obj[child1][child2]!=="undefined"){
}

This doesn't work because it will throw a JavaScript error. 这不起作用,因为它将引发JavaScript错误。 It will throw this.obj[child1] is undefined. 它将抛出this.obj [child1]未定义。 You Should always check if it's defined too. 您应该始终检查它是否也已定义。

if(this.obj[child1] && typeof this.obj[child1][child2]!=="undefined"){
}

EDIT 编辑

If you want to increase your code readability, you could use a function like this: 如果要提高代码的可读性,可以使用如下函数:

var test = {child1: {child2: "TEST"}};
alert(is_defined(test, 'child1', 'child2')); // true
alert(is_defined(test, 'child1', 'child2', 'child3')); // false

function is_defined(obj) {
    if (typeof obj === 'undefined') return false;

    for (var i = 1, len = arguments.length; i < len; ++i) {
        if (obj[arguments[i]]) {
            obj = obj[arguments[i]];
        } else if (i == (len - 1) && typeof obj[arguments[i] !== 'undefined']) {
            return true;
        } else {
            return false;
        }
    }

    return true;
}

使用undefined代替“ undefined”或尝试null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM