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

问题描述 投票:1回答:1

我需要计算小数位数,并附带此解决方案(请运行有效的代码段::

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子句并打印出来“不是整数”。但这是行不通的。您能帮我弄清楚哪里出了问题吗?

javascript prototype
1个回答
4
投票

在草率模式下,用于this之类的原始方法的decimalCounter将是原始[,因此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())
© www.soinside.com 2019 - 2024. All rights reserved.