组合比较/“太空飞船" JavaScript中的运算符(< =>)? [英] Combined Comparison / "Spaceship" Operator (<=>) in Javascript?

查看:101
本文介绍了组合比较/“太空飞船" JavaScript中的运算符(< =>)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby有一个叫做组合比较"或太空飞船"运算符的东西,它看起来像这样:<=>

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

它执行以下操作:

a <=> b :=
    if a < b then return -1
    if a = b then return  0
    if a > b then return  1

信用

Javascript中是否有类似的运算符?如果没有,我怎么能得到相同的结果?

Is there a similar Operator in Javascript? If not, how can I end up with the same result?

@ madox2 建议使用Math.sign(a - b),它适用于数字,但不适用于数组(要比较数组,您需要使用array.length).

@madox2 suggested using Math.sign(a - b), which works for number, but not arrays (to compare arrays you need to use array.length).

它在Internet Explorer,Safari或所有移动浏览器中也不起作用(请参阅

It also does not work in Internet Explorer, Safari or all Mobile Browsers (see MDN)

@duques_l 此处找到了一个函数.它运作良好,您可以在 JSFiddle

@duques_l found a function here. It works very well, you can test it on JSFiddle

唯一的问题是,如果字符串不具有可比性,则该函数将返回-1而不是nil

The only problem is if the strings are not comparable the function returns -1 instead of nil

更新: @duques_l 稍微改变了功能,现在可以正常工作了(我想无论如何,这是

Update: @duques_l changed the function a bit and now it works fine (I think so anyway, here is the JSFiddle):

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


推荐答案

据我所知,JavaScript中没有此类运算符,但您可以使用

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

Math.sign(a - b);

注意:如评论中所述,当前所有浏览器都不支持Math.sign().检查兼容性(

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

这篇关于组合比较/“太空飞船" JavaScript中的运算符(&lt; =&gt;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆