Javascript 如果参数是整数,这是一种有效的检查类型吗?
还有更好的选择吗Javascript 如果参数是整数,这是一种有效的检查类型吗?,javascript,Javascript,还有更好的选择吗 function isInteger(x) { // check if argument is a valid number and not NaN if ((typeof x !== 'number') || (x !== x)) throw Error('Not a valid number') // double binary inverse (inspired by `!!` operation) return x === ~~x; } 您可以使用。看
function isInteger(x) {
// check if argument is a valid number and not NaN
if ((typeof x !== 'number') || (x !== x)) throw Error('Not a valid number')
// double binary inverse (inspired by `!!` operation)
return x === ~~x;
}
您可以使用。看看polyfill:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
编辑:还有和函数。不要使用
x!==x
是的,函数完全按照预期工作,它检查通过函数调用发送的变量是否真的是整数,但您不需要检查(x不等于x),您可以忽略它(x!==x)
不完全是
JS数字是64位浮点,但按位运算符只支持32位整数。然后,它们截断数字
这就是为什么你可以用它们来检查一个数字是否是整数,例如
x === ~~x;
x === (x|0);
x === (x&-1);
但是,它们不适用于大于231-1或小于-232的整数:
x!==无论x
具有何种类型或值,x始终为false。说到x!==x
-要么我没有正确理解你,要么你错了(var x=1;console.log(!!x)
x=1;(x!==x)
returnsfalse
@techfoobar TryNaN
我特别感兴趣的一行是return x===~~x;
谢谢,我知道了。对解决方案本身感兴趣。链接文章中的polyfill也适用于较老的浏览器。当我们将NaN
作为参数传递时,情况如何?谢谢哦,那正是我想要的!!
x === ~~x;
x === (x|0);
x === (x&-1);
var x = Math.pow(2, 31);
x; // 2147483648
Number.isInteger(x); // true
x === ~~x; // false