如何检查地图或集合是否为空? [英] How to check if a Map or Set is empty?
问题描述
使用JavaScript中的传统对象,可以很容易地使用Object.keys
方法检查其是否为空:
const emptyObj = {};
console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty"
const populatedObj = { foo: 'bar' };
console.log(Object.keys(populatedObj).length === 0); // false, not empty
尽管有点多余,但您也可以对数组使用相同的方法:
const emptyArr = [];
console.log(Object.keys(emptyArr).length === 0); // true
const populatedArr = [1, 2, 3];
console.log(Object.keys(populatedArr).length === 0); // false
但是,ES6方便的新数据结构 Map 和 Set 的工作方式不同.如果您尝试在它们上使用Object.keys
,您将总是获得一个空数组!
const populatedSet = new Set(['foo']);
console.log(Object.keys(populatedSet).length); // 0
const populatedMap = new Map([['foo', 1]]);
console.log(Object.keys(populatedMap).length); // 0
那么检查您是否喜欢使用新的ES6结构的最佳方法是什么?另外,是否有某种单一的重载方法适用于对象,数组,地图,和集?
const populatedSet = new Set(['foo']);
console.log(populatedSet.size); // 1
const populatedMap = new Map([['foo', 1]]);
console.log(populatedMap.size); // 1
(注意:WeakMaps和WeakSets不具有size
或它们的强"对应物具有的其他几个功能,以保持其实现,并使用它们合理地编写代码.:-)它们具有相似功能的地方,它们提供相同的API,但它们不是子类.)
With a traditional object in JavaScript, it is easy enough to check if it is empty using the Object.keys
method:
const emptyObj = {};
console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty"
const populatedObj = { foo: 'bar' };
console.log(Object.keys(populatedObj).length === 0); // false, not empty
Although a bit redundant, you can use the same approach with arrays too if you like:
const emptyArr = [];
console.log(Object.keys(emptyArr).length === 0); // true
const populatedArr = [1, 2, 3];
console.log(Object.keys(populatedArr).length === 0); // false
However, ES6's handy new data structures Map and Set, don't work the same way. If you try to use Object.keys
on them you will always get an empty array!
const populatedSet = new Set(['foo']);
console.log(Object.keys(populatedSet).length); // 0
const populatedMap = new Map([['foo', 1]]);
console.log(Object.keys(populatedMap).length); // 0
So what is the best way to check whether or not your fancy new ES6 structures are populated? Also, is there some sort of single overloaded method that would work for objects, arrays, Maps, and Sets?
You use its size
property. Both Maps and Sets have it (here and here).
const populatedSet = new Set(['foo']);
console.log(populatedSet.size); // 1
const populatedMap = new Map([['foo', 1]]);
console.log(populatedMap.size); // 1
(Side note: WeakMaps and WeakSets don't have size
or several other features their "strong" counterparts have, in order to keep their implementations, and code using them, sane. :-) Where they have similar functionality, they offer the same API, but they aren't subclasses.)
这篇关于如何检查地图或集合是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!