想知道是否有任何寻找数字符号(signum函数)的重要方法?
可能是比较明显的解决方案更短/更快/更优雅的解决方案
var sign = number > 0 ? 1 : number < 0 ? -1 : 0;
Run Code Online (Sandbox Code Playgroud)
使用它,你会安全,快速
if (!Math.sign) Math.sign = function(x) { return ((x > 0) - (x < 0)) || +x; };
Run Code Online (Sandbox Code Playgroud)
现在我们有这些解决方案:
1.明显而快速
function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }
Run Code Online (Sandbox Code Playgroud)
1.1.来自kbec的修改- 一种类型转换更少,更高性能,更短[最快]
function sign(x) { return x ? x < 0 ? -1 : 1 …Run Code Online (Sandbox Code Playgroud) 1:为什么结果foo && baz不是1?因为真是1.
var foo = 1;
var baz = 2;
foo && baz; // returns 2, which is true
Run Code Online (Sandbox Code Playgroud)
2:有两个优点console.log(foo + +bar);,它们的含义是什么?
var foo = 1;
var bar = '2';
console.log(foo + +bar);
Run Code Online (Sandbox Code Playgroud)