首页 > 解决方案 > 如何防止每次触发else语句

问题描述

我对编码很陌生,很抱歉在这个初学者问题上浪费了您的时间。我正在尝试用电子书学习 JS,我的练习 atm 是编写一个程序来保存输入的姓名(名字和姓氏)和输入的性别。程序应检查名称的长度,如果名称太长或太短,则会出错。此外,这本书强迫我在被问到性别时只接受 m 或 f。如果所有内容都正确输入,它应该给出如下内容:“好吧。欢迎加入我们的社会,fName lName!啊,我们真的想要像你这样的其他(女性)男性! ”只有当您输入的内容与 m/M/f/ 不同时F 对于您的性别,应触发 else 语句,您应阅读“抱歉,我们不支持此处的性别多样性" (这是一个笑话 oc)但是 else 语句总是被触发。我在不同的练习中遇到了同样的问题,所以我希望我能从中吸取教训。

let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');

if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
  console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
  console.log('Sorry. One of your names is too short/long')
}


if (gender === 'm' || gender === 'M') { 
   console.log('Ah, we really want other males like you!');
} else {
  console.log('Sorry, we do not support gender-diversity here');
}
  
if (gender === 'f' || gender === 'F') {
  console.log('Ah, we really want other females like you!');
} else {
  console.log('Sorry, we do not support gender-diversity here');
}

标签: javascript

解决方案


您目前拥有:

if (a) {
    // Output 1
} else {
    // Output 2
}
if (b) {
    // Output 3
} else {
    // Output 4
}

acondition和 condition之间没有联系b,您不希望输出 2 仅仅因为a它是假的而发生。

相反,使用else if

let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');

if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
  console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
  console.log('Sorry. One of your names is too short/long')
}


if (gender === 'm' || gender === 'M') { 
  console.log('Ah, we really want other males like you!');
} else if (gender === 'f' || gender === 'F') {
  console.log('Ah, we really want other females like you!');
} else {
  console.log('Sorry, we do not support gender-diversity here');
}

或者您可以考虑switch

let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');

if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
  console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
  console.log('Sorry. One of your names is too short/long')
}

switch (gender) {
  case 'm':
  case 'M':
    console.log('Ah, we really want other males like you!');
    break;
  case 'f':
  case 'F':
    console.log('Ah, we really want other females like you!');
    break;
  default:
    console.log('Sorry, we do not support gender-diversity here');
    break;
}


(我强烈建议不要限制 2019 年的二元性别选择,但我认为这与你的问题有点相切。)


推荐阅读