我想检查一个数字是否为负数。我正在寻找“最简单的方法”,因此预定义的 JavaScript 函数将是最好的,但我还没有找到任何东西。这是我到目前为止所拥有的,但我认为这不是一个好方法:
function negative(number) {
if (number.match(/^-\d+$/)) {
return true;
} else {
return false;
}
}
(number < 0)
Javascript 将通过首先尝试将左侧转换为数字值来评估此表达式,然后检查它是否小于零,这似乎是您想要的。
规格和细节
x < y
的行为在
§11.8.1小于运算符 (
<
)中指定,它使用§11.8.5抽象关系比较算法。 如果
x
和
y
都是字符串,情况会有很大不同,但由于 (number < 0)
中右侧已经是数字,因此比较将尝试将左侧转换为要比较的数字数字上。如果左侧无法转换为数字,则结果为 false
。请注意,与基于正则表达式的方法相比,这可能会产生不同的结果,但根据您想要做什么,它最终可能会做正确的事情。
"-0" < 0
false
,这与-0 < 0
也是false
这一事实是一致的
(参见:带符号的零)。
"-Infinity" < 0
true
(承认无穷大)"-1e0" < 0
true
(接受科学记数法文字)"-0x1" < 0
true
(接受十六进制文字)" -1 " < 0
true
(允许某些形式的空格)
true
而不是
false
,反之亦然)。参考文献
<
)
?:
还应该说,这种形式的陈述:
if (someCondition) {
return valueForTrue;
} else {
return valueForFalse;
}
可以重构为使用三元/条件
?:
运算符 (
§11.12) 来简单地:
return (someCondition) ? valueForTrue : valueForFalse;
习惯性地使用
?:
可以使代码更加简洁和可读。
相关问题
类似以下内容:
if (someVariable) {
return true;
} else {
return false;
}
可以使用
?:
运算符重构为:
return (someVariable ? true : false);
但你也可以进一步简化为:
return Boolean(someVariable);
这会调用
Boolean
作为函数 (
§15.16.1) 来执行所需的类型转换。您可以类似地调用
Number
作为函数 (§15.17.1) 来执行数字转换。 相关问题
您的正则表达式应该可以很好地处理字符串数字,但这可能更快。 (根据上面类似答案中的评论进行编辑,不需要使用
+n
进行转换。)
function negative(number){
return number < 0;
}
* 1
部分是将字符串转换为数字。
-0
和
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
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
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