// 创建一个新的 Set 对象
const mySet = new Set();
// 使用 add 方法向 Set 中添加元素
mySet.add(1); // 添加数字 1
mySet.add(5); // 添加数字 5
mySet.add('some text'); // 添加字符串 'some text'
// 检查 Set 中是否包含某个元素
console.log(mySet.has(1)); // 输出: true
console.log(mySet.has(2)); // 输出: false
// 获取 Set 的大小
console.log(mySet.size); // 输出: 3
// 删除 Set 中的元素
mySet.delete(5); // 删除数字 5
console.log(mySet.has(5)); // 输出: false
// 清空 Set
mySet.clear(); // 清空所有元素
console.log(mySet.size); // 输出: 0
// Set 可以自动去重
const anotherSet = new Set([1, 2, 2, 3, 4, 4, 5]);
console.log(anotherSet); // 输出: Set { 1, 2, 3, 4, 5 }
new Set()
:创建一个新的 Set 对象。add(value)
:向 Set 中添加一个值,如果该值已经存在,则不会重复添加。has(value)
:检查 Set 中是否包含指定的值,返回布尔值。size
:返回 Set 中元素的数量。delete(value)
:删除 Set 中指定的值。clear()
:清空 Set 中的所有元素。[1, 2, 2, 3, 4, 4, 5]
会自动变为 [1, 2, 3, 4, 5]
。上一篇:js setdate()
下一篇:js mediarecorder
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站