我正在努力填补飞机的头等舱和经济座位。然而,当头等舱或经济舱满时,我希望有一个弹出窗口,如果有任何座位,你会想要坐在另一个座位区。如果所有座位都已满,则应该有一个弹出窗口显示飞机已满。
我有以下js小提琴:http://jsfiddle.net/Godin1/ba8Eu/
和javascript:
var seatSection;
seatsAvailable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
check = function(){
seatSection = parseInt(document.getElementById('number').value);
if (seatSection == 1) {
firstClass();
} else if (seatSection == 2) {
economy();
} else {
other();
}
}
firstClass = function() {
for (var i = 1; i <= 5; i++) {
if (seatsAvailable[i] == 0) {
window.alert("been assigned to first class seat " + i);
seatsAvailable[i] = 1;
break;
}
};
}
economy = function() {
for (var i = 6; i <= 10; i++) {
if (seatsAvailable[i] == 0) {
window.alert("been assigned to economy seat " + i);
seatsAvailable[i] = 1;
break;
}
};
}
other = function() {
window.alert("Wrong number");
}
答案 0 :(得分:0)
您可以在for
循环调用seatFound
之前添加一个布尔变量,并将其设置为false。然后在循环中,如果找到一个座位,则将其设置为true。然后你在for
循环之后检查,如果它仍然是假的,那么你知道没有开放的座位,所以你可以检查这个人是否想要更改部分。
economy
然后看起来像这样:
economy = function() {
var seatFound = false;
for (var i = 6; i <= 10; i++) {
if (seatsAvailable[i] == 0) {
window.alert("been assigned to economy seat " + i);
seatsAvailable[i] = 1;
seatFound = true;
break;
}
};
if (!seatFound && window.confirm("There are no more economy class seats
available. Would you like an first class seat?")) {
first();
}
}
此外,这是您JSFiddle
的更新版本答案 1 :(得分:0)
您可以添加一个计算已计算座位数的计数器:
var numberOfSeatsTaken = 0;
然后更新您保留的每个座位的计数器。 这是针对您的问题的更新jsfiddle。
PS。如果这是一个分配,你真的不应该要求解决你的问题 - 而是寻求帮助。
答案 2 :(得分:0)
这应该适合你: http://jsfiddle.net/itsmikem/zYEf3/4/
var seatsAvailable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var searchingElsewhere = false;
function checkAvailability() {
var sectionRequested = parseInt(document.getElementById('seatNumber').value);
switch (sectionRequested) {
case 1:
case 2:
findSeat(sectionRequested);
break;
default:
alert("Wrong number!");
}
}
function findSeat(sectionRequested) {
var searchRange = (sectionRequested == 1) ? {
from: 0,
to: 4,
section: "first class"
} : {
from: 5,
to: 9,
section: "economy"
};
var foundNextAvailable = false;
for (var i = searchRange.from; i <= searchRange.to; i++) {
if (seatsAvailable[i] == 0) {
alert(String("You're assigned to seat " + (i + 1) + " in " + searchRange.section + "."));
seatsAvailable[i] = 1;
foundNextAvailable = true;
break;
}
}
if (foundNextAvailable == false) {
if (seatsAvailable.indexOf(0) == -1) {
alert("Sorry, the plane is full.");
return;
} else {
if (confirm("Section full. Sit elsewhere in the plane?")) {
if (searchingElsewhere == false) searchingElsewhere = true;
var otherSection = (sectionRequested == 1) ? 2 : 1;
findSeat(otherSection);
}
}
}
}