簡體   English   中英

檢查 Javascript Object 中是否存在屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM