for、forEach、for in、for of用法

循环遍历数组或者对象,for、forEach、for in 、 for of 使用最多

for循环

自Javascript诞生时就有,遍历数组,for 循环的语法如下:

for (语句 1; 语句 2; 语句 3) {
要执行的代码块
}

举例说明

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)
})

输出结果

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"]

写法简单了很多,但是也存在一个局限 就是你不能中断循环(使用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
}

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

for of循环

它是ES6中新增加的语法

循环一个数组

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

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

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
}

但是可以循环一个拥有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
}

如果我们按对象所拥有的属性值进行循环,可使用内置的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
}

循环一个字符串

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

循环一个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]

循环一个Set

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

循环一个类型化数组

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

for (let value of iterable) {
console.log(value);
}
// 0
// 255

原文地址:https://www.cnblogs.com/midnight-visitor/p/10948380.html