javascript - 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
子句并打印出“不是整数”。但它不会起作用。你能帮我找出它失败的地方吗?
解决方案
在草率模式下,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())
推荐阅读
- string - 如何通过迭代bash中的变量来查找多个文件
- git - 在文件中显示差异但不允许 git 合并它们
- python - 如何在scrapy中将参数传递给pipelines.py?
- json - 反序列化之前值的 JSON 转义引号
- django - Django shell 不断失去与数据库的连接
- angular - 如果从订阅中显示,Ngx-Bootstrap 模式不会刷新数据更改
- angular - 以 DD-MM-YYYY 格式向 formControl MatDatePicker 的角度返回日期
- makefile - Make:动态执行规则
- python - 尝试使用 Python SQLAlchemy 在 Denodo 中执行查询时出错
- php - Laravel:如何在内核调度程序中引导我的模块