繁体   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