zoukankan      html  css  js  c++  java
  • JavaScript Array map()方法

    定义:对数组中的每个元素进行处理,得到新的数组;

    特点:不改变原数组;

    例子:

        const array = [1, 3, 6, 9];
        const newArray = array.map(function (value) {
          return value + 1;
        });
        console.log(newArray);
        console.log(array);

    结果:

    [2, 4, 7, 10]

    [1, 3, 6, 9]

    类似方法: for in , for , foreach

    例子:

        const newArray2 = [];
        for (var i in array) {
          newArray2.push(array[i] + 1);
        }
    
        const newArray3 = [];
        for (var i = 0; i < array.length; i++) {
          newArray3.push(array[i] + 1);
        }
    
        const newArray4 = [];
        array.forEach(function (key) {
          newArray4.push(key * key);
        })
        
        console.log(newArray2);
        console.log(newArray3);
        console.log(newArray4);
        console.log(array);
    

    结果:

    [2, 4, 7, 10]

    [2, 4, 7, 10]

    [2, 4, 7, 10]

    [1, 3, 6, 9]

    对比:

    1、.map()方法使用return,进行回调;其他方法可不需要。

    2、.map()方法直接对数组的每个元素进行操作,返回相同数组长度的数组;其他方法可扩展数组的长度。

  • 相关阅读:
    Code review
    一点心得
    有关双向追踪性的一点感觉
    测试用例分析的一点心得
    js简单的抽屉菜单
    新的感受
    linux的VPS如何分区
    PHP中Unicode转码和解码的实现
    xampp安装及配置
    js Unicode编码转换
  • 原文地址:https://www.cnblogs.com/mihoutaoguniang/p/7883616.html
Copyright © 2011-2022 走看看