简体   繁体   中英

Javascript error on Safari

I'm having some problems with javascript on desktop safari, on mobile is working fine.

When I try to run:

return Math.trunc(num * Math.pow(10, 2)) / Math.pow(10, 2);

I'm getting on console:

TypeError: 'undefined' is not a function (evaluating 'Math.trunc(num * Math.pow(10, 2))')

Any idea why can it be? On the rest of browsers is working perfectly and I have no clue why (I've never worked with safari).

Math.trunc was added in ES2015 (June 2015). Apparently the JavaScript engine in the version of Safari you're using doesn't have it yet.

You could polyfill it if it's missing:

if (!Math.trunc) {
    Object.defineProperty(Math, "trunc", {
        value: function(val) {
            return val < 0 ? Math.ceil(val) : Math.floor(val);
        }
    });
}

What about return ~~(num * Math.pow(10, 2)) / Math.pow(10, 2); ?

The ~~ operator seems to be a good replacement for Math.trunc()

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