Js中foreach()用法

js中forEach是用于遍历数组的方法,将遍历到的元素传递给回调函数,遍历的数组不能是空的要有值

forEach 语法:

// 箭头函数
[].forEach(value  => { /* … */ })
[].forEach((value , index) => { /* … */ })
[].forEach((value , index, array) => { /* … */ })

// 回调函数
[].forEach(callbackFn)

// 内联回调函数
[].forEach(function(value ) { /* … */ })
[].forEach(function(value , index) { /* … */ })
[].forEach(function(value , index, array){ /* … */ })
// value : 必须,当前元素的值
// index : 可选,当前元素的索引
// array : 可选,当前数组对象
var array = ['a', 'b', 'c'];
array.forEach(function(value) {
  console.log(value);
});

在这里插入图片描述
forEach不支持break与continue

let arr = [1, 2, 3, 4]
arr.forEach((self,index) => {
    console.log(self);
    if (self === 2) {
        break; //报错
    };
});

arr.forEach((self,index) => {
    console.log(self);
    if (self === 2) {
        continue; //报错
    };
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
forEach()是JavaScript的一个方法,用于遍历数组的每个元素,并将每个元素传递给回调函数进行处理。它有三个参数:第一个参数是一个函数,用于处理每次遍历的元素;第二个参数是可选的,用于指定回调函数的this指向的对象;第三个参数也是可选的,表示原数组。 下面是一些使用forEach()的示例: 1. 使用第一个参数函数处理数组的每个元素: var arr = [1, 3, 5]; arr.forEach(function(item){ console.log(item); }); // 输出:1 3 5 2. 使用第一个参数函数处理数组的每个元素和对应的索引: var arr = [1, 3, 5]; arr.forEach(function(item, index){ console.log(index); }); // 输出:0 1 2 3. 使用第一个参数函数处理数组的每个元素,同时访问原数组: var arr = [1, 3, 5]; arr.forEach(function(item, index, self){ console.log(self); }); // 输出:[1, 3, 5] [1, 3, 5] [1, 3, 5] 4. 使用第二个参数对象使回调函数的this指向指定对象: var obj = { '1' : 'abc', '3' : 100, '5' : 'hello' } var arr = [1, 3, 5]; arr.forEach(function(item, index, self){ console.log(this); }, obj); // 输出:{'1' : 'abc','3' : 100, '5' : 'hello'} {'1' : 'abc','3' : 100, '5' : 'hello'} {'1' : 'abc','3' : 100, '5' : 'hello'} 需要注意的是,如果原对象已经实现了forEach()方法,则会调用原对象的函数进行遍历处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [JavaScript forEach()方法](https://blog.csdn.net/HHyuang/article/details/115308427)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [javascript forEach函数实现代码](https://download.csdn.net/download/weixin_38599430/13070969)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值