简体   繁体   English

Number.isInteger(this) 在 Number.prototype 方法中不起作用

[英]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.但是,如果数字是 integer,则会引发错误。 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".我不知道为什么,因为在第一个if语句中我声明只有整数会触发该代码块,如果你删除x变量的小数,它应该进入else子句并打印出“不是整数”。 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.在草率模式下,对于像decimalCounter this的原始方法,这将是包装在 object 中的原始方法,因此Number.isInteger测试失败,因为您没有传递原始方法,而是 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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