【问题标题】:check if something is a number, in a function with an if statement [duplicate]在带有 if 语句的函数中检查某物是否是数字 [重复]
【发布时间】:2019-01-16 23:21:40
【问题描述】:

我想要一个函数接受两个参数,如果它们都是数字,就告诉我哪个更大。如果它们中的一些不是数字,我也希望它给出一个很好的输出(因为它无论如何都无法计算它)。

我已经到了能够处理 int 但不能处理浮点数的地步。它超越了我的头脑,我想知道把它写下来的最佳做法是什么。

这是我目前得到的;

var iamanumbergenius = function(a, b) {
if (Number.isInteger(a) && Number.isInteger(b)) {
if (a > b) {
  console.log('first is greater');
  } else if (b > a) {
  console.log('second is greater');
  } else {
  console.log('equality is the answer');
  }
} else { console.log('i only like nums'); }
}

抱歉,代码丑陋,直接从 chrome 开发工具中拿出来,没有什么可以不用担心按 Enter XD

很确定我错过了一些方法或类型的东西......也许还有一些布尔操作符和 number.isfloat? 在那种情况下,我不确定在操作顺序之前是什么:||和 &&..

谢谢!我对这些东西真的很陌生,所以任何帮助都会很棒:)

【问题讨论】:

  • 如果 a 和 b 已经是数字,typeof a === 'number' 将返回 true 用于整数或浮点数。
  • typeof value == 'number' 往往工作得很好。注意 NaN 也是类型号。 value % 1 === 0 也适用于整数。
  • 尝试 isNaN() 来检查是否是一个数字,而不是如果它只是一个整数。
  • 您只想检查数字还是整数?因为标题告诉数字但代码示例整数。
  • @Taplar 谢谢!原来我只是忘了把''......傻01:30我

标签: javascript function if-statement numbers


【解决方案1】:

因为typeof 对整数和浮点数都返回number,所以您可以将它用于您的函数。

typeof的演示:

console.log(typeof 1.3);

在函数中实现它的方法如下:

if (typeof a === 'number' && typeof b === 'number')

另外,因为typeof NaN === 'number', you should useisNaN()in yourif`语句太:

if (typeof a === 'number' && typeof b === 'number' && !(isNaN(a) || isNaN(b)))

【讨论】:

  • 请注意typeof NaN == 'number'。
  • 好点@RobG,我也将包括isNaN()。感谢您了解这一点。
【解决方案2】:

试试这个:

console.log(isNaN(123));
console.log(isNaN(1.23));
console.log(isNaN('stack'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多