Javascript 负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3571717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:15:17  来源:igfitidea点击:

Javascript negative number

javascriptnegative-number

提问by Adam

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 found yet anything, here is what I have so far but I don't think that this is a good way:

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

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

回答by polygenelubricants

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.

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



Specifications and details

规格和细节

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

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

The situation is a lot different if both xand yare 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.

如果xy都是字符串,情况就大不相同了,但由于右侧已经是 中的数字(number < 0),比较将尝试将左侧转换为要进行数字比较的数字。如果左侧无法转换为数字,则结果为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" < 0is false, which is consistent with the fact that -0 < 0is also false(see: signed zero).
  • "-Infinity" < 0is true(infinity is acknowledged)
  • "-1e0" < 0is true(scientific notation literals are accepted)
  • "-0x1" < 0is true(hexadecimal literals are accepted)
  • " -1 " < 0is true(some forms of whitespaces are allowed)
  • "-0" < 0false,这是与事实相一致-0 < 0也是false(参见:符号零)。
  • "-Infinity" < 0true(承认无穷大)
  • "-1e0" < 0true(接受科学记数法文字)
  • "-0x1" < 0true(接受十六进制文字)
  • " -1 " < 0true(允许某些形式的空格)

For each of the above example, the regex method would evaluate to the contrary (trueinstead of falseand vice versa).

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

References

参考

See also

也可以看看



Appendix 1: Conditional operator ?:

附录 1:条件运算符 ?:

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:

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

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.

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

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 Booleanas a function (§15.16.1) to perform the desired type conversion. You can similarly call Numberas a function (§15.17.1) to perform a conversion to number.

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

Related questions

相关问题

回答by bcherry

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 +nis not needed.)

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

回答by Iván Rodríguez Torres

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

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

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

回答by Wolph

How about something as simple as:

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

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

The * 1part is to convert strings to numbers.

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

回答by JTeam

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

在 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

回答by Hao Wu

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

如果你真的想深入研究它,甚至需要区分-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