简体   繁体   中英

Chrome/Chromium doesn't know JavaScript function Math.sign

For a scrolling feature I use some Math-functions:

transform: "rotateY("+(Math.sign(this._backlog)*Math.sqrt(Math.abs(this._backlog)))+"deg)"

While this works well in Firefox, it doesn't work in Chrome with following message:

Uncaught TypeError: Object #<Object> has no method 'sign' 

Math.abs and Math.sqrt are working.

Which function I can use in Chrome?

Math.sign is only part of the draft specification for ES6 (§20.2.2.28), which is incomplete. Support for as-yet-unspecified features is likely to be spotty from engine to engine.

MDN previously claimed that Chrome 32 supported this, but as far as I can tell that was simply wrong. My version of Chrome (36) does not support it, and MDN now claims that only FireFox supports this function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign .

But this is a pretty easy function to write yourself:

function sign(x){
    if( +x === x ) { // check if a number was given
        return (x === 0) ? x : (x > 0) ? 1 : -1;
    }
    return NaN;
}

NaN, +/-Infinity and -0 are handled correctly ( sign(-0)==-0 , sign(NaN)==NaN ), and non-numeric inputs will return NaN. If you don't care about non-numeric inputs you can use this simplified one-liner (which still handles NaN, +/-Infinity and -0 but does not check the input type):

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

一线功能:

var sign = function(n) {return n>0?1:n=0?0:-1;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM