JS中的for循环不同写法


6个月前 229次点击 来自 前端

标签: JavaScript

普通 for-i

for(let i = 0; i < 10; i++){
		...
}

for...in 循环

主要用于遍历对象的属性,当然也可用于遍历Array

for (property in obj){
	console.log(property, obj[property]);
}

ES6后语法 for...of 循环

用于迭代iterable对象(Array,Map,Set)

for (element of iterable){
	console.log(element);
}

ES5.1后语法 forEach循环

用于迭代iterable对象(Array,Map,Set)

iterable.forEach(function(value,key,iterable){
	console.log(key,value,iterable);
})

示例:

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

for (property in arr){
	console.log(property,arr[property]);
}

for (element of arr){
	console.log(element);
}

arr.forEach(function(value,key,arr){
	console.log(key,value,arr)
})

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑