admin管理员组

文章数量:1356017

The below code is working fine in Chrome, but in IE browser I am seeing the below console error:

object does not support property or method 'trunc'

Code:

var Days = (new Date(date1) - new Date(date2)) / 50;
if (Math.trunc(Days) > 45)) {
 alert("it should be less than 45 days");
}

The below code is working fine in Chrome, but in IE browser I am seeing the below console error:

object does not support property or method 'trunc'

Code:

var Days = (new Date(date1) - new Date(date2)) / 50;
if (Math.trunc(Days) > 45)) {
 alert("it should be less than 45 days");
}
Share Improve this question edited Feb 26, 2020 at 21:47 norbitrial 15.2k10 gold badges39 silver badges64 bronze badges asked Feb 25, 2020 at 20:29 DevDev 231 silver badge3 bronze badges 4
  • That's true, see on MDN - IE is not supported: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – norbitrial Commented Feb 25, 2020 at 20:30
  • 1 You'll need to use a polyfill to provide support in IE – user47589 Commented Feb 25, 2020 at 20:31
  • Yeah polyfills are the way to go! Or have your own implementation of it. – tschaka1904 Commented Feb 25, 2020 at 20:36
  • Would this work for you? – Yevhen Horbunkov Commented Feb 25, 2020 at 21:21
Add a ment  | 

3 Answers 3

Reset to default 11

Math.trunc is not supported in IE as MDN states, please read here.

Instead you could use polifylls:

if (!Math.trunc) {
    Math.trunc = function (v) {
        return v < 0 ? Math.ceil(v) : Math.floor(v);
    };
}

Hope that clarifies.

Yes, IE does not support Math.trunc, or many other features. See the MDN browser patibility table.

Your options are do the logic that .trunc is doing your self, or use an existing polyfill. Either way it would end up looking something like:

if (!Math.trunc) {
    Math.trunc = function (v) {
        return v < 0 ? Math.ceil(v) : Math.floor(v);
    };
}

It isn't built into the browser. You can use the following polyfill

Math.trunc = Math.trunc || function(x) {
  if (isNaN(x)) {
    return NaN;
  }
  if (x > 0) {
    return Math.floor(x);
  }
  return Math.ceil(x);
};

Update

After seeing a much neater version from @norbitrial this can be expressed even more succinctly as

Math.trunc = Math.trunc || function(x) {
    return x < 0 ? Math.ceil(x) : Math.floor(x);
}

本文标签: javascriptIE browser not supporting Mathtrunc()Stack Overflow