简体   繁体   English

如何摆脱该函数的第一个if语句?

[英]How can I get rid of the first if statement from this function?

I am writing a function that checks if an input is even or not. 我正在编写一个检查输入是否为偶数的函数。 There are some preset conditions for what it must output, for example both the number 42 and string "42" should read as even. 对于必须输出的内容,存在一些预设条件,例如,数字42和字符串“ 42”都应读为偶数。 Here is the code I have: 这是我的代码:

function isEven (inputEven) {
  if (inputEven === false) {
    return false;
  }
  else {
    inputEven = Number(inputEven);
    if (inputEven%2 === 0) {
      return true;
    }
    else {
      return false;
    }
  }
}

As you can see at the start of the function I have an if statement to check if the input is the boolean false. 正如您在函数开始时看到的那样,我有一个if语句来检查输入是否为布尔值false。 I had to do this as if my function is given that without that if statement it will give back true while my requirement sheet says it needs to give back false. 我必须这样做,就好像给了我的函数一样,如果没有该if语句,它将返回true,而我的需求表中则需要返回false。 Is there any way to simplify this down to a single if/else statement? 有什么方法可以简化为单个if / else语句吗?

try using parseInt instead. 尝试改用parseInt

 function isEven (inputEven) { var val = parseInt(inputEven, 10); return (!isNaN(val) && val%2 === 0); } console.log('empty', isEven()); console.log("''", isEven('')); console.log('true', isEven(true)); console.log('false', isEven(false)); console.log("'dogs'", isEven('dogs')); console.log("'true'", isEven('true')); console.log("'false'", isEven('false')); console.log('0', isEven(0)); console.log('1', isEven(1)); console.log('2', isEven(2)); console.log("'3'", isEven('3')); console.log("'4'", isEven('4')); 

Your function returns true for an empty string. 您的函数为空字符串返回true。 You wrote in comments that it should in fact return false in that case. 您在评论中写道,在这种情况下,它实际上应该返回false。 So I had to update my answer after getting that info: 因此,我必须在获取该信息后更新答案:

But first: it is almost never needed to have a pattern like this: 但首先:几乎不需要使用这样的模式:

if (something) {
    return true;
} else {
    return false;
}

You can just return the value of something in that case, possibly converted to boolean. 在这种情况下,您可以只返回something值,可能会转换为布尔值。

In your case all can be brought down to the following: 您的情况可以归结为以下几点:

function isEven(inputEven) {
    return inputEven !== false && inputEven !== "" && (Number(inputEven)%2===0);
}

I ended up using: 我最终使用:

function isEven (inputEven) {
  return parseFloat(inputEven)%2 === 0;
}

Which meets all of the requirements for the test script. 满足测试脚本的所有要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM