用法
在js中foreach和map是两种遍历数组的方法,它们可以遍历整个数组内的元素,
// 1.遍历循环:foreach和map都可以遍历一个数组集合
let arr = ["Tom","Jerry","spike"]
arr.forEach(function(item,index,array){//item 数组中的每一项元素,index 每一项元素的下标,array 数组本身
console.log("arr["+index+"]="+item);
})
console.log("-------")//分界线
arr.map(function (item,index,array) { //同foreach
console.log("arr["+index+"]="+item);
})
console.log("-------")//分界线
运行结果如下
用法上面两者完全一致,
区别
forEach,没有返回值,map有返回值
let x = arr.forEach(function(item,index,array){
return array;
})
let y = arr.map(function (item,index,array) {
return array;
})
console.log(x,y);
运行结果如下
注意 :foreach和map都无法使用break和continue中断循环
完整代码以及运行结果
// 1.遍历循环:foreach和map都可以遍历一个数组集合
let arr = ["Tom","Jerry","spike"]
arr.forEach(function(item,index,array){//item 数组中的每一项元素,index 每一项元素的下标,array 数组本身
console.log("arr["+index+"]="+item);
})
console.log("-------")//分界线
arr.map(function (item,index,array) { //同foreach
console.log("arr["+index+"]="+item);
})
console.log("-------")//分界线
// 2.forEach,没有返回值,map有返回值
let x = arr.forEach(function(item,index,array){
return array;
})
let y = arr.map(function (item,index,array) {
return array;
})
console.log(x,y);
//3.都无法使用break和continue中断循环