【问题标题】:How to print out only object values that are true?如何仅打印出真实的对象值?
【发布时间】:2019-09-13 05:34:02
【问题描述】:

我正在学习 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]);
            }
        }
    }
}

在我的 person 对象上运行 showVerified 时,我希望它只打印任何经过验证的人的年龄、名字和姓氏。

【问题讨论】:

  • this.info.isVerified = true 应该是this.info.isVerified === true
  • 单个= 是一个赋值=== 是一个比较。你也可以使用双刘海if(!!this.info.isVerified)
  • 不清楚您在问什么,因为我们看不到整个代码。 this.info 是什么? position 是什么?
  • 整个代码都在那里。这些是我的 person 对象中的函数。

标签: javascript


【解决方案1】:

我建议尝试更改您命名属性的方式,这样代码会更清晰一些。 试试

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

【讨论】:

  • 谢谢!这正是我想要的!
  • 然后接受答案以结束问题 ;) 大声笑如果你需要在 forEach() 中多于一行,请记住输入一些 {}。喜欢:.forEach(v => { console.log(v) })
【解决方案2】:

如果你不想使用过滤器,你也可以试试这个

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

【讨论】:

  • 这几乎是我正在尝试的,但没有做到。感谢您的评论!
猜你喜欢
  • 1970-01-01
  • 2019-11-15
  • 2016-05-13
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多