zoukankan      html  css  js  c++  java
  • 数组的forEach方法和map方法

    forEach

    定义:forEach是给数组的每一个元素执行一次给定的函数

    语法

    arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
    

    参数

    callback

    为每个元素执行的函数,该函数接收三个参数
    currentValue

    数组中正在处理的当前元素

    index

    数组中正在处理的当前元素的索引

    array

    函数正在操作的数组

    thisArg

    可选参数,当执行callback时,用作this的值
    例子

    var thisArg = {a:1,b:2,c:3}
    var arr = [1,2,34,56,665,434];
    arr.forEach(function(item,index,arrValue){
        console.log(item)
        console.log(index)
        console.log(arrValue)
        console.log(this)
        item = item * 2
    },thisArg)
    

    执行结果

    从上面结果中,我们可以发现,使用forEach遍历数组,可以给forEach传一个函数,该函数是当前元素执行的函数,它接收三个参数分别是数组的当前执行元素的值,当前执行元素的索引,forEach的第二个参数就是在函数中的上下文 this的指向,函数的forEach没有返回值
    ,同时,执行了callback函数后,原数组也不会发生改变

    数组的map方法

    定义:map方法返回一个新数组,新数组的值为原始数组调用函数处理后的值

    map方法数组按照原始数组元素顺序依次处理元素

    map方法不会处理空数组

    map方法不会改变原始数组

    语法

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

    参数说明

    function(currentValue, index,arr)

    数组中每个元素都会执行的函数,其中函数的参数
    currentValue:当前执行函数的数组元素

    index:当前执行函数的数组元素的索引

    arr:当前被操作的数组

    thisValue

    用作执行函数的上下文,未定型或者没传,为window

    例子

    var newArr = arr.map(function(item,index,arrValue){
        console.log(item,index)
        
        console.log(arrValue)
        console.log(this)
        return item*2
    },thisArg)
    console.log(newArr)
    console.log(arr)
    

    执行结果

  • 相关阅读:
    leetcode 189. Rotate Array 数组旋转 ---------- java
    Google test Problem A. Country Leader
    leetcode 187. Repeated DNA Sequences 求重复的DNA串 ---------- java
    mysql忘记密码(未初始化)
    leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java
    CSS3属性transform详解之(旋转:rotate,缩放:scale,倾斜:skew,移动:translate)(转载)
    bootstrap
    bootstrap使用中遇到的问题(二)
    兼容ie8 rgba()用法
    浏览器前缀
  • 原文地址:https://www.cnblogs.com/dehenliu/p/13354559.html
Copyright © 2011-2022 走看看