用法:
遍历整个数组,对数组进行操作,但不返回值。
参数:
当前值、当前位置、整个数组。
实例:
let arr = ['a', 'b', 'c']
arr.forEach(function(element, index, arr) {
console.log(index + '.' + element)
})
//0.a
//1.b
//2.c
Object.keys() 与 Array.forEach()的配合使用:
let obj = {
name: 'shen',
gendar: 'male',
age: 26
}
Object.keys(obj).forEach((value,index, arr) => {
//在回调函数中可以直接访问 obj 变量。
//配合此特性,可以访问对象中的值。
console.log("value is : %s, index is : %s, arr is : %s", value, index, arr)
})
//value is : name, index is : 0, arr is : Array(3)
//value is : gendar, index is : 1, arr is : Array(3)
//value is : age, index is : 2, arr is : Array(3)
备注:
Object.keys() 方法的作用几个是返回一个对象的属性值数组。