Javascript 如何检查给定的值是正整数还是负整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7037669/
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-24 00:22:47  来源:igfitidea点击:

How to check the value given is a positive or negative integer?

javascriptjquery

提问by Xavier

Lets say i have the value 10 assigned to a variable;

假设我将值 10 分配给一个变量;

var values = 10;

and i want to run a specific function if the value is a positive

如果值为正,我想运行一个特定的函数

if(values = +integer){ 
    //do something with positive 
} else { 
    //do something with negative values 
}

How would this be achieved?

这将如何实现?

回答by Peter Kelly

if (values > 0) {
    // Do Something
}

回答by Wolfpack'08

To just check, this is the fastest way, it seems:

只是检查一下,这是最快的方法,似乎:

var sign = number > 0 ? 1 : number == 0 ? 0 : -1; 
//Is "number": greater than zero? Yes? Return 1 to "sign".
//Otherwise, does "number" equal zero?  Yes?  Return 0 to "sign".  
//Otherwise, return -1 to "sign".

It tells you if the sign is positive (returns 1), or equal to zero (returns 0), and otherwise (returns -1). This is a good solution because 0 is not positive, and it is not negative, but it may be your var.

它告诉您符号是否为正(返回 1),或等于零(返回 0)否则为 (返回 -1)。这是一个很好的解决方案,因为 0 不是正数,也不是负数,但它可能是您的 var。

Failed attempt:

失败的尝试:

var sign = number > 0 ? 1 : -1;

...will count 0 as a negative integer, which is wrong.

...将 0 视为负整数,这是错误的。

If you're trying to set up conditionals, you can adjust accordingly. Here's are two analogous example of an if/else-if statement:

如果您尝试设置条件,则可以相应地进行调整。下面是 if/else-if 语句的两个类似示例:

Example 1:

示例 1:

number = prompt("Pick a number?");
if (number > 0){
  alert("Oh baby, your number is so big!");}
else if (number == 0){
  alert("Hey, there's nothing there!");}
else{
  alert("Wow, that thing's so small it might be negative!");}

Example 2:

示例 2:

number = prompt("Pick a number?");

var sign = number > 0 ? 1 : number == 0 ? 0 : -1;

if (sign == 1){
  alert("Oh baby, your number is so big!" + " " + number);}
else if (sign == 0){
  alert("Hey, there's nothing there!" + " " + number);}
else if (sign == -1){
  alert("Wow, that thing's so small it might be negative!" + " " + number);}

回答by stevendesu

Am I the only one who read this and realized that none of the answers addressed the "integer" part of the question?

我是唯一一个读过这篇文章并意识到没有一个答案涉及问题的“整数”部分的人吗?

The problem

问题

var myInteger = 6;
var myFloat = 6.2;
if( myInteger > 0 )
    // Cool, we correctly identified this as a positive integer
if( myFloat > 0 )
    // Oh, no! That's not an integer!

The solution

解决方案

To guarantee that you're dealing with an integer, you want to cast your value to an integer then compare it with itself.

为了保证您正在处理一个整数,您希望将您的值转换为一个整数,然后将其与自身进行比较。

if( parseInt( myInteger ) == myInteger && myInteger > 0 )
    // myInteger is an integer AND it's positive
if( parseInt( myFloat ) == myFloat && myFloat > 0 )
    // myFloat is NOT an integer, so parseInt(myFloat) != myFloat

Some neat optimizations

一些巧妙的优化

As a bonus, there are some shortcuts for converting from a float to an integer in JavaScript. In JavaScript, all bitwise operators (|, ^, &, etc) will cast your number to an integer before operating. I assume this is because 99% of developers don't know the IEEE floating point standard and would get horribly confused when "200 | 2" evaluated to 400(ish). These shortcuts tend to run fasterthan Math.flooror parseInt, and they take up fewer bytes if you're trying to eke out the smallest possible code:

作为奖励,在 JavaScript 中有一些从浮点数转换为整数的快捷方式。在 JavaScript 中,所有按位运算符(|^&等)都会在操作前将您的数字转换为整数。我认为这是因为 99% 的开发人员不了解 IEEE 浮点标准,并且当“200 | 2”评估为 400(ish)时会感到非常困惑。这些快捷方式的运行速度往往比Math.floorparseInt,如果您想尽可能减少代码,它们占用的字节更少:

if( myInteger | 0 == myInteger && myInteger > 0 )
    // Woot!
if( myFloat | 0 == myFloat && myFloat > 0 )
    // Woot, again!

But wait, there's more!

但是等等,还有更多!

These bitwise operators are working on 32-bit signed integers. This means the highest bit is the sign bit. By forcing the sign bit to zero your number will remain unchanged only if it was positive. You can use this to check for positiveness AND integerness in a single blow:

这些按位运算符正在处理 32 位有符号整数。这意味着最高位是符号位。通过强制符号位为零,您的数字只有在它为正时才会保持不变。您可以使用它在一次打击中检查正性和整数性:

// Where 2147483647 = 01111111111111111111111111111111 in binary
if( (myInteger & 2147483647) == myInteger )
    // myInteger is BOTH positive and an integer
if( (myFloat & 2147483647) == myFloat )
    // Won't happen
* note bit AND operation is wrapped with parenthesis to make it work in chrome (console)

If you have trouble remembering this convoluted number, you can also calculate it before-hand as such:

如果您无法记住这个复杂的数字,您也可以预先计算它:

var specialNumber = ~(1 << 31);

Checking for negatives

检查负数

Per @Reinsbrain's comment, a similar bitwise hack can be used to check for a negativeinteger. In a negative number, we dowant the left-most bit to be a 1, so by forcing this bit to 1 the number will only remain unchanged if it was negative to begin with:

根据@Reinsbrain 的评论,可以使用类似的按位破解来检查整数。在负数中,我们确实希望最左边的位为 1,因此通过强制此位为 1,如果数字开头为负数,则该数字将仅保持不变:

// Where -2147483648 = 10000000000000000000000000000000 in binary
if( (myInteger | -2147483648) == myInteger )
    // myInteger is BOTH negative and an integer
if( (myFloat | -2147483648) == myFloat )
    // Won't happen

This special number is even easier to calculate:

这个特殊数字更容易计算:

var specialNumber = 1 << 31;

Edge cases

边缘情况

As mentioned earlier, since JavaScript bitwise operators convert to 32-bit integers, numbers which don't fit in 32 bits (greater than ~2 billion) will fail

如前所述,由于 JavaScript 按位运算符转换为 32 位整数,因此不能容纳 32 位(大于约 20 亿)的数字将失败

You can fall back to the longer solution for these:

对于这些,您可以退回到更长的解决方案:

if( parseInt(123456789000) == 123456789000 && 123456789000 > 0 )

However even this solution fails at some point, because parseIntis limited in its accuracy for large numbers. Try the following and see what happens:

然而,即使这个解决方案在某些时候也会失败,因为parseInt它对大量数字的准确性有限。尝试以下操作,看看会发生什么:

parseInt(123123123123123123123); // That's 7 "123"s

On my computer, in Chrome console, this outputs: 123123123123123130000

在我的电脑上,在 Chrome 控制台中,输出:123123123123123130000

The reason for this is that parseInt treats the input like a 64-bit IEEE float. This provides only 52 bits for the mantissa, meaning a maximum value of ~4.5e15 before it starts rounding

这样做的原因是 parseInt 将输入视为 64 位 IEEE 浮点数。这仅为尾数提供 52 位,这意味着在开始舍入之前最大值为 ~4.5e15

回答by Mickey Puri

I thought here you wanted to do the action if it is positive.

我想在这里你想要采取行动,如果它是积极的。

Then would suggest:

然后会建议:

if (Math.sign(number_to_test) === 1) {
     function_to_run_when_positive();
}

回答by Rafal Bartoszek

1 Checking for positive value

1 检查正值

In javascript simple comparison like: value >== 0 does not provide us with answerdue to existence of -0and +0 (This is concept has it roots in derivative equations) Bellow example of those values and its properties:

在 javascript 中,简单的比较如:value >== 0由于存在-0和 +0并没有为我们提供答案(这个概念源于导数方程)这些值及其属性的波纹管示例:

var negativeZero = -0;
var negativeZero = -1 / Number.POSITIVE_INFINITY;
var negativeZero = -Number.MIN_VALUE / Number.POSITIVE_INFINITY;

var positiveZero = 0;
var positiveZero = 1 / Number.POSITIVE_INFINITY;
var positiveZero = Number.MIN_VALUE / Number.POSITIVE_INFINITY;

-0 === +0                     // true
1 / -0                        // -Infinity
+0 / -0                       // NaN
-0 * Number.POSITIVE_INFINITY // NaN

Having that in mind we can write function like bellow to check for sign of given number:

考虑到这一点,我们可以编写如下函数来检查给定数字的符号:

function isPositive (number) {
    if ( number > 0 ) { 
        return true;
    }
    if (number < 0) {
        return false;
    }
    if ( 1 / number === Number.POSITIVE_INFINITY ) {
        return true;
    }
    return false;
}

2a Checking for number being an Integer (in mathematical sense)

2a 检查数字是否为整数(在数学意义上)

To check that number is an integer we can use bellow function:

要检查该数字是否为整数,我们可以使用波纹管函数:

function isInteger (number) {
    return parseInt(number) === number;
}
//* in ECMA Script 6 use Number.isInteger

2b Checking for number being an Integer (in computer science)

2b 检查数字是否为整数(在计算机科学中)

In this case we are checking that number does not have any exponential part (please note that in JS numbers are represented in double-precision floating-point format) However in javascript it is more usable to check that value is "safe integer" (http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) - to put it simple it means that we can add/substract 1 to "safe integer" and be sure that result will be same as expected from math lessons. To illustrate what I mean, result of some unsafe operations bellow:

在这种情况下,我们正在检查数字没有任何指数部分(请注意,在 JS 中数字以双精度浮点格式表示)但是在 javascript 中检查该值是否为“安全整数”(http ://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) - 简单地说,这意味着我们可以将 1 添加/减去“安全整数”,并确保结果将是与数学课的预期相同。为了说明我的意思,下面是一些不安全操作的结果:

Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2;          // true
Number.MAX_SAFE_INTEGER * 2 + 1 === Number.MAX_SAFE_INTEGER * 2 + 4;  // true

Ok, so to check that number is safe integer we can use Number.MAX_SAFE_INTEGER / Number.MIN_SAFE_INTEGER and parseInt to ensure that number is integer at all.

好的,为了检查数字是安全整数,我们可以使用 Number.MAX_SAFE_INTEGER / Number.MIN_SAFE_INTEGER 和 parseInt 来确保数字是整数。

function isSafeInteger (number) {
    return parseInt(number) === number
    && number <== Number.MAX_SAFE_INTEGER
    && number >== Number.MIN_SAFE_INTEGER
}
//* in ECMA Script 6 use Number.isSafeInteger

回答by Ankit

simply write:

简单地写:

if(values > 0){
//positive
}
else{
//negative
}

回答by Thorben

if(values >= 0) {
 // as zero is more likely positive than negative
} else {

}

回答by Varun

if ( values > 0 ) {
    //you got a positive value
}else{
    //you got a negative or zero value    
}

回答by Gustav Barkefors

if ( values > 0 ) {
    // Yeah, it's positive
}

回答by Amitesh Maurya

To check a number is positive, negative or negative zero. Check its sign using Math.sign()method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers

检查一个数字是正数、负数还是负零。使用Math.sign()方法检查其符号 ,它将根据正负和负零或零数为您提供 -1,-0,0 和 1

 Math.sign(-3) // -1
 Math.sign(3) // 1
 Math.sign(-0) // -0
 Math.sign(0) // 0