javascript - 如何在 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!");
}
解决方案
您可以将对象添加到数组中,然后使用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!");
}
推荐阅读
- reactjs - URL 更改但页面新页面未呈现 Ionic React ,具有历史记录的 IonReactRouter
- python - 我正确理解 Prim 算法,但转移到 Python 代码太难了。我该如何实施?
- javascript - 在加载 .json 文件数据后组合 if 语句运行时出现问题(如果该 .json 函数包含 location.reload 元素)
- powerbi - 为什么我需要本地数据网关?
- kubernetes - 将 Kubernetes statefulset pod 移动到另一个节点
- python - TypeError:'float' 对象不可下标(第 144 行)
- flutter - 查找纬度/经度距离内的点 - Flutter
- python - 将新文件添加到文件夹时获取通知(python)
- github - 如何让 Github 通知我审查请求?
- linux - 有什么办法可以禁止Linux中特定目录中具有特定扩展名的文件