在 JavaScript 中获取集合的长度
How to get the Length of a Set in JavaScript
使用该size
属性获取 Set 的长度,例如mySet.size
. 该
size
属性返回Set
对象中值的数量。
当在空的上访问时Set
,该size
属性返回0
。
索引.js
const set = new Set(['a', 'b', 'c']); console.log(set.size); // 👉️ 3 set.add('d'); set.add('e'); console.log(set.size); // 👉️ 5
我们使用
Set.size
属性来获取Set
对象中元素的数量。
该属性与数组的
length
属性非常相似,并返回一个表示包含多少元素的整数Set
。As opposed to the array’s length
property, the size
property is read-only
and can’t be changed by the user.
index.js
const set = new Set(['a', 'b', 'c']); console.log(set.size); // 👉️ 3 set.size = 10; console.log(set.size); // 👉️ 3
Even though we tried to update the size of the Set
, we were unable to.
This is not the case when using the array’s length
property.
index.js
const arr = ['a', 'b', 'c']; console.log(arr.length); // 👉️ 3 arr.length = 10; console.log(arr.length); // 👉️ 10
The code sample shows that we can update the array’s length and contents by
using its length
property.
As expected, the size of the Set
object is updated when:
- you add an element to the
Set
- you remove an element from the
Set
- you use the
Set.clear()
method to remove all elements from theSet
index.js
const set = new Set(); console.log(set.size); // 👉️ 0 // ✅ add elements to the Set set.add('bobby'); set.add('hadz'); console.log(set.size); // 👉️ 2 // ✅ delete an element from the set set.delete('bobby'); console.log(set.size); // 👉️ 1 // ✅ clear the set object set.clear(); console.log(set.size); // 👉️ 0
We used the
Set.add
method to add 2 elements to the Set
object.
Accessing the size
property on the Set
returns 2
at this point.
我们使用
Set.delete
方法从Set
.
访问删除元素后size
返回的属性。1
最后,我们使用
Set.clear
方法删除了 中的所有元素Set
,因此该size
属性返回
了0
。