8

Number.prototype.isInteger = Number.prototype.isInteger || function(x) {
  return (x ^ 0) === x;
}
console.log(Number.isInteger(1));

will throw error in IE10 browser

huangxbd1990
  • 229
  • 2
  • 4
  • 10

3 Answers3

9

Apparently, IE treats DOM objects and Javascript objects separately, and you can't extend the DOM objects using Object.prototype.

IE doesn't let you use a prototype that is not native..

You'll have to make a separate function (global if you want) as

function isInteger(num) {
  return (num ^ 0) === num;
}

console.log(isInteger(1));
Muhammad Ahsan Ayaz
  • 1,867
  • 10
  • 12
  • This function works incorrect when integer presented as string. I undertstand that may be it correct for majority cases. But. If your number can be wrapped in quotes, you can use the best answer from here: [link](https://stackoverflow.com/questions/10270648/determine-if-javascript-value-is-an-integer) `Math.floor(id) == id && $.isNumeric(id)` – Pavel Samoylenko Apr 28 '18 at 12:56
2

Notwithstanding possible issues with adding to native prototypes in MSIE, your function body is inappropriate for a method added to Number.prototype.

Methods on the prototype are called on instances of the type, and the instance is passed as this (and will always be an object, not a primitive).

Therefore a more correct implementation would be:

Number.prototype.isInteger = function() {
  return (this ^ 0) === +this;
}

with usage:

(1).isInteger();

If you wanted to use Number.isInteger(n) instead, you would have had to add your function directly to the Number object, not its prototype. There's a rigorous shim for this on the MDN page for this function.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Thank you for your answer and link for Number.isInteger in MDN.But '("1").isInteger();' will throw error:Uncaught TypeError: undefined is not a function – huangxbd1990 Oct 22 '14 at 01:38
1

Create a polyfill Number.isInteger

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" &&
           isFinite(value) &&
           Math.floor(value) === value;
};

This should solve the issue related to IE.

Arunprasanth K V
  • 20,733
  • 8
  • 41
  • 71