Strange code in jQuery sources: var !== var ? x : y;

前端 未结 3 1452
清酒与你
清酒与你 2020-12-08 00:31

Recently I found one weird line in the jQuery sources (last version 1.9.1, Sizzle package, line 129 funescape function):

funescape = function( _         


        
3条回答
  •  北海茫月
    2020-12-08 00:45

    I'm piggy-backing on some of the comments here, but think this worthy information.

    Some comments on the original question have suggested that this method of checking for NaN is actually much faster than isNaN()

    When taken in conjunction with the following alternative to parseInt parseFloat we have a very fast way of converting to a number and checking its numeric state.

    Is Subtracting Zero some sort of JavaScript performance trick?

    So instead of

    function Translated(val) {
        var x = parseFloat(val);
        if (!isNaN(x)) {
            alert("Not a number");
        }
    }
    

    We can have

    function WTF(val) {
        var x = val - 0;
        if (x !== x) {
            alert("Not a number");
        }
    }
    

提交回复
热议问题