// 创建一个新的 Set 对象
const mySet = new Set();
// 向 Set 中添加元素
mySet.add(1); // 添加数字 1
mySet.add(5); // 添加数字 5
mySet.add('some text'); // 添加字符串 'some text'
mySet.add({a: 1, b: 2});// 添加对象 {a: 1, b: 2}
// Set 不会存储重复的值,所以再次添加相同的值不会生效
mySet.add(1); // 这个 1 不会被添加进去
// 检查 Set 中是否包含某个值
console.log(mySet.has(1)); // 输出 true
console.log(mySet.has(3)); // 输出 false
// 获取 Set 的大小
console.log(mySet.size); // 输出 4
// 删除 Set 中的某个值
mySet.delete(5); // 删除数字 5
console.log(mySet.has(5)); // 输出 false
// 清空 Set
mySet.clear(); // 清空整个 Set
console.log(mySet.size); // 输出 0
// 遍历 Set
const anotherSet = new Set([1, 2, 3, 4]);
anotherSet.forEach(value => {
console.log(value); // 分别输出 1, 2, 3, 4
});
// 将数组转换为 Set(自动去除重复项)
const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueValues = new Set(arrayWithDuplicates);
console.log([...uniqueValues]); // 输出 [1, 2, 3, 4, 5]
new Set():创建一个新的 Set 对象。add(value):向 Set 中添加一个值,如果该值已经存在,则不会重复添加。has(value):检查 Set 中是否包含某个值,返回布尔值。size:返回 Set 中元素的数量。delete(value):删除 Set 中的某个值。clear():清空 Set 中的所有元素。forEach(callback):遍历 Set 中的每个元素。[...set] 或者 Array.from(set) 可以将 Set 转换为数组。上一篇:js 关闭页面
下一篇:js set 去重
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站