![](/img/trans.png)
[英]Why Am I Getting “Cannot read property of undefined error” When I Can Print the Undefined Variable?
[英]why I am getting, cannot read property of undefined error?
根據快照,您使用的是chrome,Chrome很久以來就支持.forEach
。 我的猜測是,問題是由於縮小或缺少分號( ;
)
樣品
function test(){ this.name = "test"; } var a = new test()['width', 'height'].forEach(key => { console.log(key); });
您已經從代碼中省略了實際上導致問題的任何內容。
在[
之前,您必須具有引用對象的內容。
這意味着[]
語法成為讀取屬性值的語法,而不是創建數組的語法。
然后(因為使用的是逗號運算符) 'width', 'height'
解析為'height'
因此您嘗試讀取height
屬性。
由於無論對象是什么,都沒有height
屬性,因此您將獲得undefined
屬性,該屬性沒有forEach
屬性。
要解決此問題,請在上一條語句的末尾加上分號 。
代碼的第二個版本有效,因為var
語句無法遵循您之前的語法,因此會觸發自動分號插入 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.