深入浅出ES6——迭代器的演变

2018-02-08  本文已影响0人  宇cccc

在JavaScript刚刚开始萌生的时候,我们通常使用这种方式遍历数组

let arr1 = [1, 2, 3, 4];

for (let index = 0; index < arr1.length; index++) {
    const element = arr1[index];
    console.log(element); // 1 2 3 4
}

自从ES5 正式发布之后,我们可以使用 forEach 方法来遍历数组.

let arr2 = [1, 2, 3, 4];

arr2.forEach( item => {
    if (item === 3) return
    console.log(item); // 1 2 4
})

那么,你一定想尝试一下 for-in 循环

let arr3 = [1, 2, 3, 4];

for (const index in arr3) {
    if (index === 3) break
    console.log(index);   // 0 1 2 3
    console.log(typeof index); // string
}

程序再次没有按照我们预期的运行:

let arr3 = [1, 2, 3, 4];

Array.prototype.name = '看看我被遍历了没';

for (const key in arr3) {

    // 将额外的遍历属性
    // const element = arr3[key];
    // console.log(element); // 1 2 3 4 '看看我被遍历没'

    // 正确做法
    if (arr3.hasOwnProperty(key)) {
        const element = arr3[key];
        console.log(element); // 1 2 3 4
    }
}

更好的选择 for-of 循环

在ES6中增加了一种新的循环语法来解决目前的问题:

for (variable of iterable) {
    //statements
}

for...of 可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。

// 向控制台输出对象的可枚举属性
for (var key of Object.keys(someObject)) {
    console.log(key + ": " + someObject[key]);
}

深入理解

“能工摹形,巧匠窃意.” -- 巴勃罗·毕加索

ES6始终坚信这样的宗旨: 凡是新加入的特性,势必已在其他语言中得到强有力的实用性证明。
举个例子,新加入的for-of 循环像极了C++、Java、C#以及Python中的循环语句。与他们一样,这里的 for-of 循环支持语言和标准库中提供的几种不同的数据结构,它同样也是这门语言中的一个扩展点。

上一篇 下一篇

猜你喜欢

热点阅读