一、forEach
forEach是专门用来遍历数组的,可以同时得到索引值和数组元素,forEach的回调函数中,第一个是数组元素,第二个是元素索引值,只有一个参数时,是数组元素:
let arr = ['a', 'b', 'c'];
arr.forEach((item,index) => {
console.log(item, index);
})
// 'a' 0
// 'b' 1
// 'c' 2
二、for…in
for…in对字符串,数组,对象都可以进行遍历,并且得到的是索引值或者键名,拿不到元素值或属性值:
let str = 'string';
let arr = ['a', 'b', 'c'];
let obj = {
name: 'xiaoming',
age: '18',
gender: 'male'
}
for (let item in str) {
console.log('in',item);
}
// 0
// 1
// 2
// 3
// 4
// 5
for (let index in arr) {
console.log('in',index);
}
// 0
// 1
// 2
for (let key in obj) {
console.log('in',key);
}
// name
// age
// gender
三、for…of
for…of是ES6的新语法,用来遍历可迭代的数据,得到的是元素值:
let str = 'string';
let arr = ['a', 'b', 'c'];
for (let item of str) {
console.log('of',item);
}
// s
// t
// r
// i
// n
// g
for (let item of arr) {
console.log('of',item);
}
// a
// b
// c
可迭代的数据:
- String字符串
- Array数组
- Map映射
- Set集合
- arguments函数实参对象
- Nodelist节点列表