如果没有任何If语句有效,我如何使else语句起作用

时间:2018-02-08 16:44:53

标签: javascript jsbin

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语句。

2 个答案:

答案 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都是正确的(您不会在问题中抱怨它们)。因此,您必须期望其他值不是onoff ...

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');
}