【JavaScript】- forEach的用法

forEach(function)   用于调用数组的每个元素,并将元素传递给回调函数。原数组不变数组的每个元素执行一次提供的函数。没有返回值

注意点:

1. 如果只有一个参数,那么就是 数组内容

2. 它的语句结构里面不支持break、continue和return语句 ,break和continue会直接报错,不会读取return语句

语法:

let array = ['a', 'b', 'c']

array.forEach(function(element) {
  console.log(element)                输出 a b c
})

或

array.forEach((a)=> {
  console.log(a);                    输出 a b c
})        

属性:

foreach方法主要有三个参数,分别是数组内容、数组索引、整个数组

    let arr = ['a', 'b', 'c']

                    // 数组内容、数组索引、数组本身
    arr.forEach(function (value, index, array) {
      console.log(value)
      console.log(index)
      console.log(array)
    })

输出:    
a                    // 数据内容
0                    // 索引
['a', 'b', 'c']      // 数组本身
b
1
['a', 'b', 'c']
c
2
['a', 'b', 'c']

 对比:

forEach() 方法对数组的每个元素执行一次提供的函数。总是返回undefined;

 let arr = [1,2,3,4];
    
 arr.forEach(alert); 
 
//    等价于:
    
 let arr = [1, 2, 3, 4];
 
 for (let k = 0, length = arr.length; k < length; k++) {
    
  alert(array[k]);
    
    } 

forEach和map的区别:

区别主要在于map有返回值,而forEach没有返回值

forEach:

let arr = [0,2,4,6,8];
 var newArr = arr.forEach(item=>{
            console.log(item)
            return item/2;
 },this);
 console.log(newArr);

// 输出
0
2
4
6
8
undefined

map:

 let arr = [0,2,4,6,8];
 let newArr = arr.map(item=>{
            console.log(item)
            return item/2;
 },this);
 console.log(newArr);

// 输出
0
2
4
6
8
[0,1,2,3,4]

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值