判断整数的方法
1 利用parseInt
const isInteger(target) => parseInt(target) === target
注意,parseInt
只会返回两个类型的结果,数值或者NaN
2 利用取余运算
const isInteger(target) => typeof target === 'number' && target % 1 === 0
3 利用Math方法
const isInteger(target) => Math.round(target) === target;
const isInteger(target) => Math.ceil(target) === target;
const isInteger(target) => Math.floor(target) === target
4 利用按位运算符号
const isInteger(target) => (~~target) === target;
const isInteger(target) => (target | 0) === target;
const isInteger(target) => (target & -1) === target;
JavaScript在按位运算时,会将小数部分抛弃,只对整数部分操作。
5 利用Number.isInterger
方法
ES6提供的方法
const isInteger(target) => Number.isInteger(target);
直接取整的方法
取整最常用的方法是parseInt
,但是这个方法处理科学计数法表示的小数时是错误的:
parseInt(0.01); // 0
parseInt(1e-6); // 1
parseInt(0.0000001); // 1,相当于
可以使用按位运算来取整,可以使用双取反、有符号右移0位,与0按位或,与-1按位与,与0按位异或
注意,这只适用于32位有符号数字所能表示的最小和最大整数之间的数字,即[-2147483648,2147483647]
const getInteger = num => ~~num;
const getInteger = num => num >> 0;
const getInteger = num => num | 0;
const getInteger = num => num ^ 0;
const getInteger = num => num & -1;