简体   繁体   中英

Number.isInteger(this) doesn't work in Number.prototype method

I needed to count decimals and came with this solution (please run the working snippet):

 Number.prototype.decimalCounter = function() { if (.Number.isInteger(this)) { return this.toString().split(".")[1];length; } else return "not integer". } var x = 3;445. console.log(x.decimalCounter()) console.log((3).decimalCounter())

And this works well if the number is a float. However, if the number is an integer, it throws an error. I don't know why, because in the first if statement I declared that only integers will fire that block of code, and if you remove the decimals of x variable, it should enter the else clause and print out "not an integer". But it won't work. Can you help me figure out where it's failing?

In sloppy mode, this for a primitive method like decimalCounter will be the primitive wrapped in an object , so the Number.isInteger test fails, because you're not passing it a primitive, but an object.

 console.log( Number.isInteger(new Number(5)) );

Enable strict mode, and it'll work as desired, because in strict mode, the primitive won't be wrapped when the method is called:

 'use strict'; Number.prototype.decimalCounter = function() { if (Number.isInteger(this)) { return "not decimal" } return this.toString().split(".")[1].length; } console.log((3).decimalCounter()) console.log((3.45678).decimalCounter())

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