簡體   English   中英

如何僅打印出真實的對象值?

[英]How to print out only object values that are true?

我正在學習Javascript,並且正在制作一個簡單的用戶驗證對象。 我需要一個將console.log僅將“ isVerified”設置為true的用戶使用的函數。

我嘗試了許多方法,包括循環和if語句。 函數名稱在下面是“ showVerified”。

var person = {
    info: [],
    displayPerson: function() {
        console.log('People', this.info);
    },
    addPerson: function(age, firstName, lastName) {
        this.info.push({
            age: age,
            firstName: firstName,
            lastName: lastName,
            isVerified: false
        });
        this.displayPerson();
    },
    deletePerson: function(position) {
        this.info.splice(position, 1);
        this.displayPerson();
    },
    verifyPerson: function(position) {
        this.info[position].isVerified = true;
        this.info[position].firstName = this.info[position].firstName.toUpperCase();
        this.displayPerson();
    },
    showVerified: function() {
        for (var key in this.info) {
            if (this.info.isVerified = true) {
                console.log(this.info.isVerified[key]);
            }
        }
    }
}

我要在我的人員對象上運行showVerified時發生的情況是,它僅打印出已驗證人員的年齡,名字和姓氏。

我建議嘗試更改命名屬性的方式,這樣代碼就更清晰了。 嘗試

showVerified: function() {
        this.info.filter(x => x.isVerified).forEach(v => console.log(v))
    }

如果您不想使用過濾器,也可以嘗試使用

this.info.forEach(person => {
   if(person.isVerified){
   console.log(person);
   }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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