// 使用 JavaScript 的 Set 对象来存储唯一的值
// 创建一个新的 Set 对象
const mySet = new Set();
// 向 Set 中添加元素
mySet.add(1); // 添加数字 1
mySet.add(5); // 添加数字 5
mySet.add('some text'); // 添加字符串 'some text'
mySet.add({name: "John"}); // 添加对象 {name: "John"}
// 检查 Set 中是否包含某个元素
console.log(mySet.has(1)); // 输出: true
console.log(mySet.has(2)); // 输出: false
// 获取 Set 中的元素数量
console.log(mySet.size); // 输出: 4
// 删除 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, 3]);
for (let item of anotherSet) {
console.log(item); // 分别输出 1, 2, 3
}
// 将 Set 转换为数组
const setToArray = Array.from(anotherSet);
console.log(setToArray); // 输出: [1, 2, 3]
new Set():创建一个新的 Set 对象。add(value):向 Set 中添加一个新值。has(value):检查 Set 中是否包含某个值,返回布尔值。size:返回 Set 中元素的数量。delete(value):从 Set 中删除指定的值。clear():清空 Set 中的所有元素。for...of:用于遍历 Set 中的每个元素。Array.from(set):将 Set 转换为数组。上一篇:js get
下一篇:js isnan
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站