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

后端 未结 2 1770
[愿得一人]
[愿得一人] 2021-02-07 00:11

Ruby has something called a Combined Comparison or \"Spaceship\" Operator, it looks like this: <=>

It does the following:

a <=>          


        
2条回答
  •  离开以前
    2021-02-07 00:22

    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;
      }
    }
    

提交回复
热议问题