首页 > 解决方案 > Number.isInteger(this) 在 Number.prototype 方法中不起作用

问题描述

我需要计算小数并附带此解决方案(请运行工作片段):

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())

如果数字是浮点数,这很有效。但是,如果数字是整数,则会引发错误。我不知道为什么,因为在第一个if语句中我声明只有整数会触发该代码块,如果你删除x变量的小数,它应该进入else子句并打印出“不是整数”。但它不会起作用。你能帮我找出它失败的地方吗?

标签: javascriptprototype

解决方案


在草率模式下,this对于像这样的原始方法decimalCounter将是包装在 object 中的原始方法,因此Number.isInteger测试失败,因为您没有将原始方法传递给它,而是传递给它的对象。

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

启用严格模式,它会按需要工作,因为在严格模式下,调用方法时不会包装原语:

'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())


推荐阅读