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?
这将如何实现?
13 个解决方案
#1
134
if (values > 0) {
// Do Something
}
#2
19
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);}
#3
14
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 faster than Math.floor
or 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时,他们会非常困惑。这些捷径往往比数学快。层或parseInt,如果你想要尽可能地保存最小的代码,它们占用的字节就更少:
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 negative integer. In a negative number, we do want 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 parseInt
is 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控制台,输出:123123123123130000
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 float。这只为尾数提供了52位,这意味着在开始四舍五入之前最大的值为~4.5e15
#4
8
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();
}
#5
6
1 Checking for positive value
In javascript simple comparison like: value >== 0 does not provide us with answer due to existence of -0 and +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)
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)
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 /号码。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
#6
5
if ( values > 0 ) {
// Yeah, it's positive
}
#7
5
simply write:
简单地写:
if(values > 0){
//positive
}
else{
//negative
}
#8
5
if(values >= 0) {
// as zero is more likely positive than negative
} else {
}
#9
4
if ( values > 0 ) {
//you got a positive value
}else{
//you got a negative or zero value
}
#10
2
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,以正负0或0为基础
Math.sign(-3) // -1
Math.sign(3) // 1
Math.sign(-0) // -0
Math.sign(0) // 0
#11
0
I use in this case and it works :)
我在这个例子中使用,它是有效的
var pos = 0;
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
if (sign === 0) {
zero++;
} else if (sign === 1 ) {
pos++;
} else {
neg++;
}
}
#12
0
You should first check if the input value is interger with isNumeric() function. Then add the condition or greater than 0. This is the jQuery code for it.
您应该首先检查输入值是否与isNumeric()函数相交。然后添加条件或大于0。这是它的jQuery代码。
function isPositiveInteger(n) {
return ($.isNumeric(n) && (n > 0));
}
#13
-1
For checking positive integer:
检查正整数:
var isPositiveInteger = function(n) {
return ($.isNumeric(n)) && (Math.floor(n) == n) && (n > 0);
}
#1
134
if (values > 0) {
// Do Something
}
#2
19
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);}
#3
14
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 faster than Math.floor
or 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时,他们会非常困惑。这些捷径往往比数学快。层或parseInt,如果你想要尽可能地保存最小的代码,它们占用的字节就更少:
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 negative integer. In a negative number, we do want 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 parseInt
is 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控制台,输出:123123123123130000
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 float。这只为尾数提供了52位,这意味着在开始四舍五入之前最大的值为~4.5e15
#4
8
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();
}
#5
6
1 Checking for positive value
In javascript simple comparison like: value >== 0 does not provide us with answer due to existence of -0 and +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)
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)
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 /号码。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
#6
5
if ( values > 0 ) {
// Yeah, it's positive
}
#7
5
simply write:
简单地写:
if(values > 0){
//positive
}
else{
//negative
}
#8
5
if(values >= 0) {
// as zero is more likely positive than negative
} else {
}
#9
4
if ( values > 0 ) {
//you got a positive value
}else{
//you got a negative or zero value
}
#10
2
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,以正负0或0为基础
Math.sign(-3) // -1
Math.sign(3) // 1
Math.sign(-0) // -0
Math.sign(0) // 0
#11
0
I use in this case and it works :)
我在这个例子中使用,它是有效的
var pos = 0;
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
if (sign === 0) {
zero++;
} else if (sign === 1 ) {
pos++;
} else {
neg++;
}
}
#12
0
You should first check if the input value is interger with isNumeric() function. Then add the condition or greater than 0. This is the jQuery code for it.
您应该首先检查输入值是否与isNumeric()函数相交。然后添加条件或大于0。这是它的jQuery代码。
function isPositiveInteger(n) {
return ($.isNumeric(n) && (n > 0));
}
#13
-1
For checking positive integer:
检查正整数:
var isPositiveInteger = function(n) {
return ($.isNumeric(n)) && (Math.floor(n) == n) && (n > 0);
}