JS里的循环方法:for,forEach,for…in,for…of

for循环

老经典了

for (var index = 0; index < myArray.length; index++) {
  console.log(myArray[index]);
}

foreach循环

写法简单了许多,但也有短处:你不能中断循环(使用break语句或使用return语句)

myArray.forEach(function (value) {
  console.log(value);
});

for…in 循环

for...in循环常用于循环带有字符串key的对象,不推荐用它来循环数组

var obj = {a:1, b:2, c:3};
    
for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}
 
// 输出:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

for…of循环

for...of循环是ES6新加入的,可以说是foreach和for...in的加强结合体,可以遍历多种数据

//循环一个数组(Array):
let iterable = [10, 20, 30];
 
for (let value of iterable) {
  console.log(value);
}
// 10
// 20
// 30

//循环一个字符串:
let iterable = "boo";
 
for (let value of iterable) {
  console.log(value);
}
// "b"
// "o"
// "o"

//循环一个类型化的数组(TypedArray):
let iterable = new Uint8Array([0x00, 0xff]);
 
for (let value of iterable) {
  console.log(value);
}
// 0
// 255

//循环一个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
发布了69 篇原创文章 · 获赞 15 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Yanzudada/article/details/104664518