81

我想检查一个数字是否为负数。我正在寻找最简单的方法,所以预定义的 JavaScript 函数是最好的,但我还没有找到任何东西。这是我到目前为止所拥有的,但我认为这不是一个好方法:

function negative(number) {
  if (number.match(/^-\d+$/)) {
    return true;
  } else {
    return false;
  }
}
4

7 回答 7

331

而不是编写一个函数来做这个检查,你应该能够使用这个表达式:

(number < 0)

Javascript 将通过首先尝试将左侧转换为数字值来评估此表达式,然后再检查它是否小于零,这似乎是您想要的。


规格和细节

的行为x < y§11.8.1 小于运算符 ( <)中指定,它使用§11.8.5 抽象关系比较算法

如果xy都是字符串,情况会大不相同,但由于右侧已经是 中的数字(number < 0),因此比较将尝试将左侧转换为要进行数字比较的数字。如果左侧不能转换为数字,则结果为false

请注意,与基于正则表达式的方法相比,这可能会产生不同的结果,但取决于您尝试做什么,它最终可能会做正确的事情。

  • "-0" < 0is ,这与isfalse的事实一致 (参见:有符号零)。-0 < 0false
  • "-Infinity" < 0true(确认无穷大)
  • "-1e0" < 0true(接受科学记数法文字)
  • "-0x1" < 0true(接受十六进制文字)
  • " -1 " < 0true(允许使用某些形式的空格)

对于上述每个示例,正则表达式方法的计算结果会相反(true而不是false反之亦然)。

参考

也可以看看


附录一:条件运算符?:

还应该说这种形式的陈述:

if (someCondition) {
   return valueForTrue;
} else {
   return valueForFalse;
}

可以重构为使用三元/条件?:运算符(§11.12)来简单地:

return (someCondition) ? valueForTrue : valueForFalse;

的惯用用法?:可以使代码更加简洁易读。

相关问题


附录二:类型转换函数

Javascript 具有您可以调用以执行各种类型转换的函数。

类似于以下内容:

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

可以使用?:运算符重构:

return (someVariable ? true : false);

但您也可以进一步简化为:

return Boolean(someVariable);

Boolean作为一个函数(第 15.16.1 节)调用以执行所需的类型转换。您可以类似地调用Number函数 ( §15.17.1 ) 来执行到数字的转换。

相关问题

于 2010-08-26T02:49:33.673 回答
14
function negative(n) {
  return n < 0;
}

您的正则表达式应该适用于字符串数字,但这可能更快。(从上面类似答案的评论中编辑,+n不需要转换。)

于 2010-08-26T02:54:52.813 回答
8

这是一个老问题,但它有很多观点,所以我认为更新它很重要。

ECMAScript 6 带来了函数Math.sign(),它返回数字的符号(如果是正数,则返回 -1,如果是负数,则返回 -1)或如果不是数字,则返回 NaN。参考

您可以将其用作:

var number = 1;

if(Math.sign(number) === 1){
    alert("I'm positive");
}else if(Math.sign(number) === -1){
    alert("I'm negative");
}else{
    alert("I'm not a number");
}
于 2015-12-02T09:27:14.563 回答
3

像这样简单的事情怎么样:

function negative(number){
    return number < 0;
}

* 1部分是将字符串转换为数字。

于 2010-08-26T02:50:04.510 回答
1

在 ES6 中,您可以使用 Math.sign 函数来确定,

1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN


console.log(Math.sign(1))        // prints 1 
console.log(Math.sign(-1))       // prints -1
console.log(Math.sign(0))        // prints 0
console.log(Math.sign("abcd"))   // prints NaN
于 2017-08-14T11:07:30.903 回答
1

如果你真的想深入研究它,甚至需要区分-0and 0,这里有一种方法。

function negative(number) {
  return !Object.is(Math.abs(number), +number);
}

console.log(negative(-1));  // true
console.log(negative(1));   // false
console.log(negative(0));   // false
console.log(negative(-0));  // true
于 2020-04-14T05:16:49.893 回答
0

一种很好的方法,也可以检查正面和负面...

function ispositive(n){
    return 1/(n*0)===1/0
}

console.log( ispositive(10) )  //true
console.log( ispositive(-10) )  //false
console.log( ispositive(0) )  //true
console.log( ispositive(-0) )  //false

本质上Infinity-Infinity因为0===-0// true

于 2021-04-03T14:16:13.033 回答