Uncaught TypeError: Cannot read property of undefined In JavaScript

当脚本遇到未初始化的变量或对象时,通常会抛出如上图所示的错误。

Decription

'Undefined'是全局对象的属性。如果没有为变量赋值,则为'undefined'类型。当求值变量没有任何赋值时,代码也会返回未定义的值。

Code structure

function test(t) {      //defining a function
  if (t === undefined) {       //if t=undefined, call tt
        console.log(t.tt)      //call tt member from t
  }
  return t;    
}
var a;    //a is a variable with undefined value
console.log(test(a)); //function call

Error

运行以上代码后,将会看到一个错误提示:

Debugging

需要在代码中判断是否变量是 undefined

if (typeof(jsvariable) == 'undefined') {
  ...
}

https://codeburst.io/uncaught-typeerror-cannot-read-property-of-undefined-in-javascript-c81e00f4a5e3

猜你喜欢

转载自www.cnblogs.com/ryanzheng/p/10259719.html