forEach
orEach 方法为数组中含有有效值的每一项执行一次 callback 函数,那些已删除(使用 delete 方法等情况)或者从未赋值的项将被跳过(不包括那些值为 undefined 或 null 的项)
callback函数会被依次传入三个函数:
-
数组的当前项的值
-
数组当前项的索引
-
数组对象本身
let arr = ['a','b','c'];
arr[3] = 'd';
arr.name = 'Tom';
arr.forEach((value,index,data)=>{
console.log(value,index,data)
})
//a 0 ["a", "b", "c", "d", name: "Tom"]
//b 1 ["a", "b", "c", "d", name: "Tom"]
//c 2 ["a", "b", "c", "d", name: "Tom"]
//d 3 ["a", "b", "c", "d", name: "Tom"]
let arr = [{name:'Jack',age:12},{name:'Lucy',age:9},{name:'Tom',age:15}];
arr[3] = 'd';
arr.name = 'Tom';
arr.forEach((value,index,data)=>{
console.log(value,index,data)
})
//{name:'Jack',age:12} 0 [{name:'jack',age:12},{name:'lucy',age:9},{name:'Tom',age:15},'d',name:'Tom']
//{name:'Lucy',age:9} 1 [{name:'jack',age:12},{name:'lucy',age:9},{name:'Tom',age:15},'d',name:'Tom']
//{name:'Tom',age:15} 2 [{name:'jack',age:12},{name:'lucy',age:9},{name:'Tom',age:15},'d',name:'Tom']
//d 3 [{name:'jack',age:12},{name:'lucy',age:9},{name:'Tom',age:15},'d',name:'Tom']
缺点:不能跳出forEach循环,break命令与return命令都不能奏效
for...in...
Array.prototype.age = 18;
let arr = [1,2,3];
arr[3] = 4;
arr.name = 'Jack';
for(let index in arr){
console.log('arr['+index+'] = '+arr[index])
}
//arr[0] = 1
//arr[1] = 2
//arr[2] = 3
//arr[3] = 4
//arr[name] = Jack
//arr[age] = 18
缺点:
-
数组的键名是数字,但是for...in循环是以字符串作为键名“0”,“1”,“2”等等
-
for...in循环不仅遍历数字键名,还会遍历手动添加的其他键,甚至包括原型链上的键
-
某些情况下,for...in循环会以任意顺序遍历键名
for...in循环主要是为遍历对象而设计的,不适用于遍历数组。
补充:
- for-in 循环遍历的是对象的属性,而不是数组的索引
- Array 在 Javascript 中是一个对象, Array 的索引是属性名
- for-in 遍历属性的顺序并不确定,即输出的结果顺序与属性在对象中的顺序无关,也与属性的字母顺序无关,与其他任何顺序也无关
for...of...
Array.prototype.age = 18;
let arr = [1,2,3];
arr[3] = 4;
arr.name = 'Jack';
for(let index of arr){
console.log(index)
}
//1
//2
//3
//4
优点:
-
有着同for...in一样的简介语法,但是没有for...in那些缺点
-
不同于forEach方法,他可以与break、continue、return配合使用
-
提供了遍历所有数据结构的统一操作接口
补充:
for...in循环的是key for...of循环的是value