let music = 'on';
let phone = 'on';
if (music === 'off' || phone === 'off'){
console.log('Music or phone is off');
} if (music === 'on' && phone === 'on') {
console.log('music is playing');
} if (music === 'off') {
console.log('music is off');
} if (phone === 'off') {
console.log('phone is off');enter code here
} if (music === 'off' && phone === 'off') {
console.log('Both Phone and Music if off');
} else {
console.log('Dont know why music is not playing');
}
如果if语句都不适用,那么无论我只想显示else语句,它都会显示else语句。
答案 0 :(得分:3)
您想使用if-else-if
而不是if-else
。
let music = 'on';
let phone = 'on';
if (music === 'off' || phone === 'off'){
console.log('Music or phone is off');
} else if (music === 'on' && phone === 'on') {
console.log('music is playing');
} else if (music === 'off') {
console.log('music is off');
} else if (phone === 'off') {
console.log('phone is off');enter code here
} else if (music === 'off' && phone === 'off') {
console.log('Both Phone and Music if off');
} else {
console.log('Dont know why music is not playing');
}
所以现在只有在没有if执行时才执行。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
答案 1 :(得分:0)
假设您的if
都是正确的(您不会在问题中抱怨它们)。因此,您必须期望其他值不是on
或off
...
let music = 'on';
let phone = 'on';
if (music === 'off' || phone === 'off'){
console.log('Music or phone is off');
}
if (music === 'on' && phone === 'on') {
console.log('music is playing');
}
if (music === 'off') {
console.log('music is off');
}
if (phone === 'off') {
console.log('phone is off');enter code here
}
if (music === 'off' && phone === 'off') {
console.log('Both Phone and Music if off');
}
//else {
if (music === 'on' && phone !== 'off' && phone !== 'on' ||
phone === 'on' && music !== 'off' && music !== 'on' ) { // that's all that is left to test
console.log('Dont know why music is not playing');
}