美文网首页
JavaScript Array map() 方法

JavaScript Array map() 方法

作者: 李赫尔南 | 来源:发表于2022-12-05 09:30 被阅读0次

      map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。map() 方法按照原始数组元素顺序依次处理元素。
    注意:1. map()不会改变原始数组。
       2. map()不会对空数组进行检测。

    语法

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

    参数说明

    参数说明.png

    返回值: 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

    1. 遍历和进行运算
    const arr = [1,4,9,16]
    console.log(arr.map((item) => Math.sqrt(item)))
    
    输出内容.png
     var studentList = [
        {"id": 1, "name": "李赫尔南", "age": 18},
        {"id": 2, "name": "李小白", "age": 28},
        {"id": 3, "name": "李小小", "age": 8},
    ]
    console.log(studentList.map(item =>{
        return {name: item.name, age: item.age}
    })) 
    
    输出内容.png

    注意:
     map()的遍历会跳过空位置,但是它会保留空的元素!

    const arr = [1, , , 3, ,2 ,]
    console.log(arr.map((item) => item*2))
    
    输出内容.png

    相关文章

      网友评论

          本文标题:JavaScript Array map() 方法

          本文链接:https://www.haomeiwen.com/subject/orbbfdtx.html