如果满足条件,我希望能够停止执行程序。这是一个学校项目,所以我无法从IF语句中进行更改。
while (peopleInGroup[0] > i) {
ageOfPeopleInGroup.push(prompt("How old are you? " + i));
i++;
}
//If any one of the people in the group is under 13, then all members are prompted the rules of the movie thearter. If statements were choosen because it's possible none of the people in the group are under 13.//
if (ageOfPeopleInGroup[0]< 13) {
alert("If someone is under the age of 13, they must be accompanied by someone 18 years of age or older.")
答案 0 :(得分:1)
你在这里犯了一些错误。
首先你的循环不会迭代,因为你总是指向第一个元素(peopleInGroup[0]
)。您需要一个变量来迭代(peopleInGroup[i]
)。但是while循环并不是最自然的,有更好的数组迭代方法,如for
,forEach
等。
接下来你的if条件在循环之外,如果条件满足,你可以把它放在它里面并使用break
退出循环,例如:
while(i < peopleInGroup.length) {
if (peopleInGroup[i].age > 13) {
hasUnderagePeople = true;
break;
}
i++;
}
但是有一些数组方法可以告诉您项目是否满足条件,例如Array.prototype.some:
const hasSomeUnderagePeople = peopleInGroup.some(person => person.age <= 13);
在旧式javascript中相当于:
var hasSomeUnderagePeople = peopleInGroup.some(function(person) {
return person.age <= 13;
});
然后你的提示:
if (hasSomeUnderagePeople) {
alert('If someone is under the age of 13, they must be accompanied by someone 18 years of age or older.')
}
这假设数组中的每个项都是具有age属性的对象。目前还不清楚你的物品实际上是由什么组成的。
答案 1 :(得分:0)
我不知道你能改变多少结构,但这可能是你想要的东西:
var numOfPeople=parseInt(prompt("How many persons are there?"));
var underaged=false;
var ages=[];
for(var i=0;i<numOfPeople;i++){
var age=parseInt(prompt("How old are you?"));
ages.push(age);
if(age<13)
underaged=true;
}
if(underaged)
alert("Blablabla, 13, blablabla...");
这里的想法是,所有年龄段都会被要求,如果其中任何一个年龄低于13,则会出现在变量underaged
中,并导致仅在结尾处显示警报,并且仅曾经,对整个集团而言。
如果您不想存储所有年龄段,那么使用while
+ break
更有意义:
var numOfPeople=parseInt(prompt("How many persons are there?"));
while(numOfPeople>0){
if(parseInt(prompt("How old are you?"))<13){
alert("Blablabla, 13, blablabla...");
break;
}
numOfPeople--;
}
此变体开始询问年龄,如果有未成年人,则显示警报并停止询问。如果所有年龄段都很好,它就会结束而不显示任何东西。
答案 2 :(得分:0)
while (peopleInGroup[0] > i) {
var age = prompt("How old are you? " + i);
if(age < 13){
//If any one of the people in the group is under 13, then all members are prompted the rules of the movie thearter. If statements were choosen because it's possible none of the people in the group are under 13.//
alert("If someone is under the age of 13, they must be accompanied by someone 18 years of age or older.")
break;
} else {
ageOfPeopleInGroup.push(age);
}
i++;
}