“虚假或空虚”在JavaScript中:如何将{}和[]视为false [英] "Falsy or empty" in JavaScript: How to treat {} and [] as false
问题描述
[]
和 {}
在javascript中是真实的。
[]
and {}
are truthy in javascript.
但是我想把它们当作假的,我很想知道如何用尽可能少的字符来做它:没有外部库或单独的函数,以及小到足以舒适地适应条件的括号。
But I want to treat them as false, and I would love to know how to do it in the least number of characters possible: without external libraries or separate functions, and small enough to fit comfortably between the parentheses of a conditional.
换句话说:
检查未知变量(可能是任何类型)的最简洁方法是什么?如果 ,则返回
false
适用:a)它已经是假的;或b)它是{}
或[]
?
What is the most concise way possible to check an unknown variable (that could be of any type) and return
false
if either of these apply: a) it's already falsy; or b) it's{}
or[]
?
推荐答案
鉴于你有变量 x
来检查:
!(!x || x.length === 0 || JSON.stringify(x) === '{}')
这里我们从后面开始,让我们检查 x
是否为空:
Here we go from the back, lets check if x
is empty:
- 它可能已经是假的:
!x
- 它是数组,其长度为零:
x.length === 0
- 它正是
{}
对象:JSON.stringify(x)==='{}'
- it may be already falsy:
!x
- it is Array and its length is zero:
x.length === 0
- it is exactly
{}
object:JSON.stringify(x) === '{}'
小心 JSON.stringify
方法。它适用于大多数现代浏览器,但如果您需要支持IE6,7则不适用。您应该查看 caniuse / JSON 。
Be careful with JSON.stringify
method. It is available for majority of modern browsers, but not for IE6,7 if you need to support them. You should check at caniuse/JSON.
任何这个条件为真会导致变量 x
为空。
Any of this conditions being true will result in variable x
to be empty.
所以我们需要或者( ||
)和外部!
反转结果以检查 x
是否不是空白。
So we need or's (||
) and outer !
to invert result to check if x
is not empty.
编辑:
更简洁的方式做第3次检查将是由于@David备注( JSON.stringify
不适用于包含等方法的对象{a:function(){console.log(test) );}}
):
More concise way to do 3rd check would be due to @David remark (JSON.stringify
will not work with object containing methods like {a: function(){ console.log("test"); }}
):
(function (x){ for (key in x) { return 0; } return 1; })(x)
因此得到的表达式为:
!(!x || x.length === 0 || (function (x){ for (key in x) { return 0; } return 1; })(x))
编辑:
如果您只想支持现代浏览器,请使用ecmascript 5功能:
If you wanna support only modern browser, than just use ecmascript 5 feature:
// Given x is defined
!(!x || typeof x === 'object' && !Object.keys(x).length)
这篇关于“虚假或空虚”在JavaScript中:如何将{}和[]视为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!