zoukankan      html  css  js  c++  java
  • JS ES6语法之:map()方法

    MDN web docs上面说:

    map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

    并举了个例子:

    var array1 = [1,4,9,16];
    const map1 = array1.map(x => x *2);
    console.log(map1);
    

    打印结果为:

    > Array [2,8,18,32]
    

    而我这样写时:

    var array1 = [1, 4, 9, 16];
     
    const map1 = array1.map(x => {
        if (x == 4) {
            return x * 2;
        }
    });
     
    console.log(map1);
    

    打印结果为:

    > Array [undefined, 8, undefined, undefined]
    

    为什么会出现三个undefined呢?而不是我预期的[1,8,9,16]。

    这样写只是增加了一个条件,即x的值为4时才乘以2,之所以会出现undefined,是因为map()方法创建了一个新数组,但新数组并不是在遍历完array1后才被赋值的,而是每遍历一次就得到一个值。所以,下面这样修改后就正确了:

    var array1 = [1, 4, 9, 16];
     
    const map1 = array1.map(x => {
        if (x == 4) {
            return x * 2;
        }
        return x;
    });
    

    这里注意箭头函数有两种格式:
    1.只包含一个表达式,这时花括号和return都省略了。
    2.包含多条语句,这时花括号和return都不能省略。

    大家可以参考:ES6标准新增了一种新的函数

  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/wjlbk/p/12633392.html
Copyright © 2011-2022 走看看