1. 程式人生 > >Uncaught TypeError: Cannot read property of undefined In JavaScript

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