// 创建一个新的 Set 对象
const mySet = new Set();
// 添加值到 Set 中
mySet.add(1); // Set(1) { 1 }
mySet.add(5); // Set(2) { 1, 5 }
mySet.add(5); // Set(2) { 1, 5 } (重复的值不会被添加)
// 检查 Set 中是否存在某个值
console.log(mySet.has(1)); // true
console.log(mySet.has(3)); // false
// 删除 Set 中的某个值
mySet.delete(5); // true (删除成功)
console.log(mySet.has(5)); // false
// 获取 Set 的大小
console.log(mySet.size); // 1
// 清空 Set
mySet.clear();
console.log(mySet.size); // 0
// 遍历 Set
const anotherSet = new Set([1, 2, 3]);
anotherSet.forEach(value => {
console.log(value); // 依次输出 1, 2, 3
});
// 将 Set 转换为数组
const setToArray = Array.from(anotherSet);
console.log(setToArray); // [1, 2, 3]
new Set()
:创建一个新的 Set 对象。add(value)
:向 Set 中添加一个值,如果该值已存在,则不会重复添加。has(value)
:检查 Set 中是否包含某个值,返回布尔值。delete(value)
:从 Set 中删除某个值,返回布尔值表示是否删除成功。size
:获取 Set 中元素的数量。clear()
:清空 Set 中的所有元素。forEach(callback)
:遍历 Set 中的每个元素。Array.from(set)
:将 Set 转换为数组。上一篇:js set集合
下一篇:js new set
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站