首页 > 解决方案 > 如何在 if-else 语句中考虑 4 个变量

问题描述

我有一个包含 4 个变量的代码,名为 Alex John Billy 和 Bob。我创建了一个 if-else 语句,现在我只希望如果this.age在 14 下找到任何 var 的值时执行 if 语句,如果所有 var 都超过 14 则执行 else 语句

但现在只执行 else 语句,我假设它是因为 2/4 vars 的this.age值超过 14。我的问题是我如何准确地考虑所有 vars

function person(name, age){
    this.name = name;
    this.age = age;
}

var Alex = new person("Alex", 15);
var John = new person("John", 16);
var Billy = new person("Billy", 13);
var Bob = new person("Bob", 11);

if(this.age < 14){
    document.write("oops!");
}
else{
    document.write("yay!");
}

标签: javascript

解决方案


您可以将对象添加到数组中,然后使用Array.prototype.some()检查是否至少有一个包含的对象的年龄低于 14 岁。

function person(name, age){
    this.name = name;
    this.age = age;
}

persons = [];

persons.push(new person("Alex", 15));
persons.push(new person("John", 16));
persons.push(new person("Billy", 13));
persons.push(new person("Bob", 11));

if(persons.some(p => p.age < 14)){
    document.write("oops!");
}
else{
    document.write("yay!");
}


推荐阅读