gpt4 book ai didi

javascript - JavaScript 中的 "Falsy or empty": How to treat {} and [] as false

转载 作者:行者123 更新时间:2023-11-30 08:05:00 25 4
gpt4 key购买 nike

[]{} 在 javascript 中是真实的。

但我想将它们视为 false,并且我很想知道如何以尽可能少的字符数来做到这一点:没有外部库或单独的函数,并且足够小以舒适地放在条件的括号之间。

换句话说:

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 []?

最佳答案

数组最简洁的方式是!arr.length。当然,这是假设您没有向数组添加任何非索引属性(这是一件完全有效的事情)。而作为 Qantas 94 Heavy在评论中指出,空数组可以将其 length 设置为非零值,而不会获得任何实际条目。

对象更棘手。什么是“空”对象?一个完全没有属性的?一个没有可枚举属性的?其原型(prototype)的属性(如果有)如何?

如果没有可枚举属性为你做,在 ES5 中你可以使用 !Object.keys(obj).length。如果你不能指望 ES5,你必须有一个循环:

var empty = true;
var key;
for (key in obj) {
// Add an `obj.hasOwnProperty(key)` check here if you want to filter out prototype properties
empty = false;
break;
}

...这显然相当笨拙。

你说过你不想要单独的函数,但当然这是最好的方法:

var isFalsey = (function() {
var toString = Object.prototype.toString;

function isFalsey(x) {
var key;

if (!x) {
return true;
}
if (typeof x === "object") {
if (toString.call(x) === "[object Array]") {
return !x.length; // Assumes no non-element properties in the array
}
for (key in x) {
// Add an `x.hasOwnProperty(key)` check here if you want to filter out prototype properties
return false;
}
return true;
}

return false;
}

return isFalsey;
})();

Example with tests ( source )

关于javascript - JavaScript 中的 "Falsy or empty": How to treat {} and [] as false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com