For each···in / For···in / For···of

在开发过程中经常需要循环遍历数组或者对象,forEach、for in 、 for of这三种方法使用最多 但却一值傻傻分不清楚。。今天来一个大区分。。
for循环

其实除了这三种方法以外还有一种最原始的遍历,自Javascript诞生起就一直用的 就是for循环,它用来遍历数组

var arr = [1,2,3,4]
for(var i = 0 ; i< arr.length ; i++){
    console.log(arr[i])
}

    1
    2
    3
    4

forEach

从ES5开始 Javascript内置了forEach方法 用来遍历数组

let arr = ['a', 'b', 'c', 'd']
arr.forEach(function (val, idx, arr) {
    console.log(val + ', index = ' + idx) // val是当前元素,index当前元素索引,arr数组
    console.log(arr)
})

    1
    2
    3
    4
    5

输出结果:

a, index = 0
(4) ["a", "b", "c", "d"]
b, index = 1
(4) ["a", "b", "c", "d"]
c, index = 2
(4) ["a", "b", "c", "d"]
d, index = 3
(4) ["a", "b", "c", "d"]

    1
    2
    3
    4
    5
    6
    7
    8

写法简单了很多,但是也存在一个局限 就是你不能中断循环(使用break语句或使用return语句)。
for…in

for-in循环实际是为循环”enumerable“对象而设计的

let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o in obj) {
    console.log(o)    //遍历的实际上是对象的属性名称 a,b,c,d
    console.log(obj[o])  //这个才是属性对应的值1,2,3,4
}

    1
    2
    3
    4
    5

for - in 也可用来循环数组,但一般并不推荐
for…of

它是ES6中新增加的语法
循环一个数组

let arr = ['China', 'America', 'Korea']
for (let o of arr) {
    console.log(o) //China, America, Korea
}

    1
    2
    3
    4

但是它并不能循环一个普通对象

let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of obj) {
    console.log(o)   //Uncaught TypeError: obj[Symbol.iterator] is not a function
}

    1
    2
    3
    4

但是可以循环一个拥有enumerable属性的对象。
如果我们按对象所拥有的属性进行循环,可使用内置的Object.keys()方法

let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.keys(obj)) {
    console.log(o) // a,b,c,d
}

    1
    2
    3
    4

如果我们按对象所拥有的属性值进行循环,可使用内置的Object.values()方法

let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.values(obj)) {
    console.log(o) // 1,2,3,4
}

    1
    2
    3
    4

循环一个字符串

let str = 'love'
for (let o of str) {
    console.log(o) // l,o,v,e
}

    1
    2
    3
    4

循环一个Map

let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

for (let entry of iterable) {
  console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

循环一个Set

let iterable = new Set([1, 1, 2, 2, 3, 3]);

for (let value of iterable) {
  console.log(value);
}
// 1
// 2
// 3

    1
    2
    3
    4
    5
    6
    7
    8

循环一个类型化数组

let iterable = new Uint8Array([0x00, 0xff]);

for (let value of iterable) {
  console.log(value);
}
// 0
// 255
---------------------
作者:一个慢
来源:CSDN
原文:https://blog.csdn.net/one_girl/article/details/80192899
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/xuye9893/p/10054859.html