本文介绍了Number.sign()在javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道是否有发现数的标志,其平凡的方式(符号函数)?
可能会较短/更快/更优雅的解决方案比明显的

Wonder if there are any nontrivial ways of finding number's sign (signum function)?
May be shorter / faster / more elegant solutions than the obvious one

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


短节选

使用这一点,你就可以安全快速


Short excerpt

Use this and you'll be safe and fast

function sign(x) {
    return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}


结果

目前,我们有以下解决方案:


Results

For now we have these solutions:

1 明显,快速

function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }


1.1 修改从 kbec - 一种类型的投少了,更好的性能,更短的 [最快]


1.1. Modification from kbec - one type cast less, more performant, shorter [fastest]

function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }

注意:符号(0) - &GT; 1

2 优雅,短,没有那么快的 [慢]

2. Elegant, short, not so fast [slowest]

function sign(x) { return x && x / Math.abs(x); }

注意:号(+ - 无限远) - &GT;为NaN 符号(0) - &GT;为NaN

由于无限的是JS法律若干这种解决方案似乎并不完全正确。

As of Infinity is a legal number in JS this solution doesn't seem fully correct.

3。艺术......但速度很慢的 [慢]

3. The art... but very slow [slowest]

function sign(x) { return (x > 0) - (x < 0); }


4。使用位移位
    快,但符号(负无穷大) - &GT; 0


4. Using bit-shift
fast, but sign(-Infinity) -> 0

function sign(x) { return (x >> 31) + (x > 0 ? 1 : 0); }


5。类型安全的 [megafast]


5. Type-safe [megafast]

好像浏览器(尤其是Chrome的V8)做一些神奇的优化和该解决方案原来是要比别人更好的性能,甚至比(1.1),尽管它包含了2个额外的操作和逻辑上从来没有不能更快。

! Seems like browsers (especially chrome's v8) make some magic optimizations and this solution turns out to be much more performant than others, even than (1.1) despite it contains 2 extra operations and logically never can't be faster.

function sign(x) {
    return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}


工具

  • jsperf preformance测试;
  • 小提琴 - 类型转换试验;

  • Tools

    • jsperf preformance tests;
    • fiddle - type-cast tests;
    • 改进,欢迎!

      • Andrey Tarantsov - +100 for the art, but sadly it is about 5 times slower than the obvious approach

      弗雷德里克·哈米迪 - 不知何故最upvoted答案(其时写),它还挺酷的,但它绝对不是事情应该如何是完成后,恕我直言。此外,它不能正确处理无限的数字,这也是数字,你知道的。

      Frédéric Hamidi - somehow the most upvoted answer (for the time writing) and it's kinda cool, but it's definitely not how things should be done, imho. Also it doesn't correctly handle Infinity numbers, which are also numbers, you know.

      kbec - 是显而易见的解决方案的改进。这并不是说革命性的,但把所有在一起我认为这个方法是最好的。投票给他:)

      kbec - is an improvement of the obvious solution. Not that revolutionary, but taking all together I consider this approach the best. Vote for him :)

      推荐答案

      快速的解决方案更多优雅版:

      More elegant version of fast solution:

      var sign = number?number<0?-1:1:0
      

      问候

      这篇关于Number.sign()在javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:57