我想检入一个JS对象(例如:{ x:false,y:true }),如果某些属性是布尔型的,或者它们是(null ||未定义的)。
在JS或下划线中有没有一种简单的方法来检查这一点而不做
(obj.x != null || obj.x != undefined)?
发布于 2017-06-08 15:58:28
我在下划线中找到了一个简单的方法:
_.isBoolean(obj.x) 我现在知道了,如果x为Thanks to Rajesh或未定义,obj.x != null会返回相同的值。
我更喜欢下划线函数,因为它是可读的,但null比较是原生JS,似乎更有效,更简单。
发布于 2017-06-08 15:59:42
您可以只使用标准的typeof运算符,如果是布尔值,则返回'boolean'。
console.log(typeof undefined === 'boolean'); // false
console.log(typeof null === 'boolean'); // false
console.log(typeof true === 'boolean'); // true
console.log(typeof false === 'boolean'); // true
发布于 2017-06-08 16:00:33
typeof运算符可以返回它是boolean还是其他任何值
参考here
https://stackoverflow.com/questions/44429888
复制相似问题