一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

js中forEach的用法之forEach与for之间区别代码解析

时间:2022-03-29 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下js中forEach的用法之forEach与for之间区别代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、定义和用法

forEach()调用数组的每个元素,并将元素传递给回调函数。

注意:forEach()对于空数组是不会执行回调函数的。

用法:

array.forEach(function(currentValue, index, arr), thisValue)

1==> currentValue 必需。当前元素

2==> index可选。当前元素的索引值,是数字类型的

3==> arr 可选。当前元素所属的数组对象

4==>可选。传递给函数的值一般用 "this" 值。

如果这个参数为空, "undefined" 会传递给 "this" 值

forEach 的注意点:

forEach()本身是不支持的continue与break语句的。

我们可以通return语句实现continue关键字的效果

二、运用场景

1.运用的场景(计算数字之和)

计算数组所有元素相加的总和:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = 0;
arr.forEach((currentIndex, index, curArr) => {
    sum += currentIndex
        // sum=sum+currentIndex
})
console.log('之和是', sum);

2.运用的场景(给原始数组新增key值)

//给原始数组的每一项新增一个属性值
let arr = [{
  id: '001',
  name: '张三1'
}, {
  id: '002',
  name: '张三2'
}, {
  id: '003',
  name: '张三2'
}];
//给原始数组的每一项新增一个属性值
arr.forEach((item, index) => {
  item['addAttrs'] = ''
})
console.log('arr', arr);

--使用for of来出处理--
for (let item of arr) {
    item['index'] = ''
}
console.log('arr', arr);

三、forEach 跳出循环

1.forEach 跳出当前的循环 return

//内容为3,不遍历该项
var arr = [1, 2, 3];
arr.forEach(function(item) {
    if (item === 3) {
        return;
    }
    console.log(item);
});

2.forEach结合try跳出整个循环

找到id为002,然后终止整个循环,返回当前这一项的值。

使用try-catch完成的

代码如下:

let arr = [{
  id: '001',
  name: '张三1'
}, {
  id: '002',
  name: '张三2'
}, {
  id: '003',
  name: '张三2'
}];

// 使用forEach跳出整个循环,使用rty-catch
function useForeach(Arr) {
  let obj = {}
  try {
    Arr.forEach(function(item) {
      if (item.id == '002') {
        // 找到目标项,赋值。然后抛出异常
        obj = item
        throw new Error('return false')
      }
    });
  } catch (e) {
    // 返回id===002的这一项的数据
    return obj
  }
}
console.log(useForeach(arr))

3.forEach 与for循环的区别 【面试题】

1==> for可以用continue跳过当前循环中的一个迭代,forEach 用continue会报错。但是可以使用return来跳出当前的循环

2==> for可以使用break来跳出整个循环,forEach正常情况无法跳出整个循环。

如果面试官问:如果非要跳出forEach中的循环,可以抛出一个异常来处理

热门栏目