欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

1.3遍历

程序员文章站 2022-07-13 12:47:31
...

for of
有着同for…in一样的简洁语法,但是没有for…in那些缺点。
不同于forEach方法,它可以与break、continue和return配合使用。
提供了遍历所有数据结构的统一操作接口。



        const map = new Map();
        map.set('first', 'hello');
        map.set('second', 'world');
        for (let [key, value] of map) {
            console.log(key, 'is', value);
        }

        var array11 = [5.3, 6, 9, 8, 10];
        // ==数组for of,遍历keys
        for (let key of array11.keys()) {
            console.log("打印key", key);
        }
        // ==数组for of,遍历values
        for (let value of array11.values()) {
            console.log("打印value", value);
        }
        // ==数组遍历keys与values
        for (let [key, value] of array11.entries()) {
            console.log(key, 'is', value);
            if (value === 8) {
                break
            }
        }

原生具备 Iterator 接口的数据结构如下。Iterator接口主要供for…of消费

Array
Map
Set
String
TypedArray
函数的 arguments 对象
NodeList 对象

Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构Set和Map)

相关标签: for of 遍历