Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js set遍历

作者:疯狂灭世   发布日期:2026-08-02   浏览:91

// 创建一个新的 Set 对象
const mySet = new Set([1, 2, 3, 4, 5]);

// 使用 for...of 循环遍历 Set
console.log("使用 for...of 循环遍历 Set:");
for (let item of mySet) {
    console.log(item);
}

// 使用 forEach 方法遍历 Set
console.log("\n使用 forEach 方法遍历 Set:");
mySet.forEach(function(value, valueAgain, set) {
    console.log(value);
});

// 使用 Array.from 将 Set 转换为数组再遍历
console.log("\n使用 Array.from 将 Set 转换为数组再遍历:");
Array.from(mySet).forEach(item => console.log(item));

// 使用扩展运算符将 Set 转换为数组再遍历
console.log("\n使用扩展运算符将 Set 转换为数组再遍历:");
[...mySet].forEach(item => console.log(item));

解释说明:

  1. 创建 Set 对象:我们首先创建了一个包含数字 1 到 5 的 Set 对象。
  2. for...of 循环:可以直接遍历 Set 中的每个元素,语法简单直观。
  3. forEach 方法Set 提供了 forEach 方法,可以传递一个回调函数来处理每个元素。注意,forEach 的回调函数接收三个参数:当前值、当前值(重复)、和 Set 对象本身。
  4. Array.from 和 扩展运算符:这两种方法可以将 Set 转换为数组,然后使用数组的遍历方法(如 forEach)进行遍历。

上一篇:js 自定义函数

下一篇:js static

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站