forEach 的注意及使用

1.forEach()方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组

2.

 forEach方法中的function回调有三个参数,
  第一个参数为:当前正在遍历的元素
  第二个参数为:当前元素索引
  第三个参数为:原数组本身

  [].forEach(function(value, index, array))

3.

      3.1 这个方法没有返回值,仅仅是遍历数组中的每一项,不对原来数组进行修改
  但是可以自己通过数组索引来修改原来的数组
  3.2 forEach()不能遍历对象,可以使用for in

4.

    4.1 您不能使用break语句中断循环,也不能使用return语句返回到外层函数
 4.2 ES5推出的,实际性能比for还弱

var obj = [1,2,3,4,5,6]
var res = obj.forEach(function(item, index, arr) {
  arr[index] = item * 10;
})
console.log(obj)
输出结果为 [10, 20, 30, 40, 50, 60]

var obj = [1,2,3,4,5,6]
var res = obj.forEach(function(item, index, arr) {
 return  item * 10;
})

console.log(res)

输出结果为 undefined

 


 
 
posted @ 2020-06-10 10:13  有肌肉的小眼睛  阅读(416)  评论(0)    收藏  举报