如何判断一个数是否为负数?

发布于 2024-09-16 05:03:07 字数 280 浏览 4 评论 0原文

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

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

I want to check if a number is negative. I’m searching for the easiest way, so a predefined JavaScript function would be the best, but I didn’t find anything yet. Here is what I have so far, but I don’t think that this is a good way:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

踏雪无痕 2024-09-23 05:03:07

您应该能够使用此表达式,而不是编写函数来执行此检查:

(number < 0)

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


规格和详细信息

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

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

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

  • <代码>“-0”< 0 为false,这与-0 一致。 0 也是 false
    (请参阅:签名零)。
  • <代码>“-无穷大”< 0 为 true(确认无穷大)
  • "-1e0" "-1e0" "-1e0" "-1e0" "-1e0" 0true (接受科学记数法文字)
  • "-0x1" "-0x1" "-0x1" "-0x1" 0true (接受十六进制文字)
  • " -1 " " -1 " " -1 " " -1 " " -1 " 0true (允许某些形式的空格)

对于上面的每个示例,正则表达式方法将得出相反的结果(true 而不是 false ,反之亦然)。

参考文献

另请参阅


附录 1:条件运算符 ?:

还应该说,这种形式的语句:

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

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

return (someCondition) ? valueForTrue : valueForFalse;

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

相关问题


附录 2:类型转换函数

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

如下所示:

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

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

return (someVariable ? true : false);

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

return Boolean(someVariable);

这将 Boolean 调用为函数 (§15.16.1) 执行所需的类型转换。您可以类似地将 Number 作为函数调用 (§15.17 .1) 执行数字转换。

相关问题

Instead of writing a function to do this check, you should just be able to use this expression:

(number < 0)

Javascript will evaluate this expression by first trying to convert the left hand side to a number value before checking if it's less than zero, which seems to be what you wanted.


Specifications and details

The behavior for x < y is specified in §11.8.1 The Less-than Operator (<), which uses §11.8.5 The Abstract Relational Comparison Algorithm.

The situation is a lot different if both x and y are strings, but since the right hand side is already a number in (number < 0), the comparison will attempt to convert the left hand side to a number to be compared numerically. If the left hand side can not be converted to a number, the result is false.

Do note that this may give different results when compared to your regex-based approach, but depending on what is it that you're trying to do, it may end up doing the right thing anyway.

  • "-0" < 0 is false, which is consistent with the fact that -0 < 0 is also false
    (see: signed zero).
  • "-Infinity" < 0 is true (infinity is acknowledged)
  • "-1e0" < 0 is true (scientific notation literals are accepted)
  • "-0x1" < 0 is true (hexadecimal literals are accepted)
  • " -1 " < 0 is true (some forms of whitespaces are allowed)

For each of the above example, the regex method would evaluate to the contrary (true instead of false and vice versa).

References

See also


Appendix 1: Conditional operator ?:

It should also be said that statements of this form:

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

can be refactored to use the ternary/conditional ?: operator (§11.12) to simply:

return (someCondition) ? valueForTrue : valueForFalse;

Idiomatic usage of ?: can make the code more concise and readable.

Related questions


Appendix 2: Type conversion functions

Javascript has functions that you can call to perform various type conversions.

Something like the following:

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

Can be refactored using the ?: operator to:

return (someVariable ? true : false);

But you can also further simplify this to:

return Boolean(someVariable);

This calls Boolean as a function (§15.16.1) to perform the desired type conversion. You can similarly call Number as a function (§15.17.1) to perform a conversion to number.

Related questions

ぃ双果 2024-09-23 05:03:07

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

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

This is an old question but it has a lot of views so I think that is important to update it.

ECMAScript 6 brought the function Math.sign(), which returns the sign of a number (1 if it's positive, -1 if it's negative) or NaN if it is not a number. Reference

You could use it as:

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");
}
长梦不多时 2024-09-23 05:03:07
function negative(n) {
  return n < 0;
}

您的正则表达式对于字符串数字应该可以正常工作,但这可能更快。 (根据上面类似答案中的评论进行编辑,不需要使用 +n 进行转换。)

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

Your regex should work fine for string numbers, but this is probably faster. (edited from comment in similar answer above, conversion with +n is not needed.)

梨涡少年 2024-09-23 05:03:07

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

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

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

How about something as simple as:

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

The * 1 part is to convert strings to numbers.

西瓜 2024-09-23 05:03:07

如果您确实想深入研究它,甚至需要区分 -00,这里有一种方法。

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

If you really want to dive into it and even need to distinguish between -0 and 0, here's a way to do it.

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
千鲤 2024-09-23 05:03:07

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

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


console.log(Math.sign(3))        // prints 1 
console.log(Math.sign(-3))       // prints -1
console.log(Math.sign(0))        // prints 0
console.log(Math.sign("abcd"))   // prints NaN

In ES6 you can use Math.sign function to determine if,

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


console.log(Math.sign(3))        // prints 1 
console.log(Math.sign(-3))       // prints -1
console.log(Math.sign(0))        // prints 0
console.log(Math.sign("abcd"))   // prints NaN
谁的新欢旧爱 2024-09-23 05:03:07

一种还检查正负的好方法...

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

An nice way that also checks for positive and negative also...

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

essentially compares Infinity with -Infinity because 0===-0// true

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文