将value
转化为一个安全整数
。
使用 Math.max()
和 Math.min()
找到最接近的安全value
。
使用 Math.round()
将其转化为整数
。
const toSafeInteger = num =>
Math.round(
Math.max(
Math.min(
num,
Number.MAX_SAFE_INTEGER
),
Number.MIN_SAFE_INTEGER
)
);
例子:
// 3
toSafeInteger('3.2');
// 9007199254740991
toSafeInteger(Infinity);