Javascript "cannot read property "bar" of undefined

This question already has an answer here:

  • Detecting an undefined object property 40 answers

  • If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

    if (thing && thing.foo)
       alert(thing.foo.bar);
    

    I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

    function someFunc(parameterName) {
       if (parameterName && parameterName.foo)
           alert(parameterName.foo.bar);
    }
    

    You can safeguard yourself either of these two ways:

    function myFunc(thing) {
        if (thing && thing.foo && thing.foo.bar) {
            // safe to use thing.foo.bar here
        }
    }
    
    function myFunc(thing) {
        try {
            var x = thing.foo.bar;
            // do something with x
        } catch(e) {
            // do whatever you want when thing.foo.bar didn't work
        }
    }
    

    In the first example, you explicitly check all the possible elements of the variable you're referencing to make sure it's safe before using it so you don't get any unplanned reference exceptions.

    In the second example, you just put an exception handler around it. You just access thing.foo.bar assuming it exists. If it does exist, then the code runs normally. If it doesn't exist, then it will throw an exception which you will catch and ignore. The end result is the same. If thing.foo.bar exists, your code using it executes. If it doesn't exist that code does not execute. In all cases, the function runs normally.

    The if statement is faster to execute. The exception can be simpler to code and use in complex cases where there may be many possible things to protect against and your code is structured so that throwing an exception and handling it is a clean way to skip execution when some piece of data does not exist. Exceptions are a bit slower when the exception is thrown.


    复合检查:

       if (thing.foo && thing.foo.bar) {
          ... thing.foor.bar exists;
       }
    
    链接地址: http://www.djcxy.com/p/22634.html

    上一篇: 如何检查元素是否未定义?

    下一篇: Javascript“无法读取未定义的属性”栏“