[英]Check if property exists in Javascript Object
class User{ constructor(username,description){ this.username = username this.description = description } printInfo(info){ if (info in this){ return info } } } let newUser = new User("testUsername","testDescription") newUser.printInfo(username)
當我嘗試這個時,它在第 17 行給我一個關於Uncaught ReferenceError
的錯誤。
您在傳遞用戶名屬性名稱時忘記了引號。 傳遞的username
參數必須是字符串newUser.printInfo("username")
。
如果沒有引號,它將嘗試引用名為username
的(不存在的)全局變量。
請注意,您的printInfo
function 將只返回屬性名稱(與參數相同),而不是實際值。 如果要返回用戶名值,則必須以this[info]
的形式訪問該鍵:
...
printInfo(info){
if (info in this){
return this[info];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.