Combined Comparison / “Spaceship” Operator (<=>) in Javascript?

心已入冬 提交于 2019-12-03 05:09:55
madox2

As far as I know there is no such operator in JavaScript but you can use Math.sign() function:

Math.sign(a - b);

NOTE: As was mentioned in comments, Math.sign() is not currently supported by all browsers. Check for compatibility (MDN).

from: http://sabrelabs.com/post/48201437312/javascript-spaceship-operator

improved version:

function spaceship(val1, val2) {
  if ((val1 === null || val2 === null) || (typeof val1 != typeof val2)) {
    return null;
  }
  if (typeof val1 === 'string') {
    return (val1).localeCompare(val2);
  } else {
    if (val1 > val2) {
      return 1;
    } else if (val1 < val2) {
      return -1;
    }
    return 0;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!