Array map function doesn't change elements

前端 未结 4 1502
Happy的楠姐
Happy的楠姐 2020-12-11 20:22

In JavaScript, I have an array, which is

array = [true, false]

In some cases, I am trying to initialize this array

array.map(i         


        
相关标签:
4条回答
  • 2020-12-11 20:56

    If your mapping is simple, you can do:

    var array = [true, false];
    array = array.map(_ => false);
    
    console.log(array);
    // [false, false]
    
    0 讨论(0)
  • 2020-12-11 21:02

    JavaScript Array map() Method

    *)creates a new array with the results of calling a function for every array element and it calls the provided function once for each element in an array, in order.

    Note: map() Method does not execute the function for array elements without values and it does not change the original array.

    more details

    0 讨论(0)
  • 2020-12-11 21:09

    .map() method is not mutable, check out its return value:

    var arr2 = array.map(item => false)
    console.log(arr2)
    

    In functional programming, it's recommended that values do not change often, and JavaScript borrowed it. At least for .map() and .reduce() this is true. Make sure you know .map() well.

    0 讨论(0)
  • 2020-12-11 21:12

    Array map function is working fine. The map() method creates a new array with the results of calling a provided function on every element in this array. map() does not mutate the array on which it is called.

    var array = [true, false]
    
    
    
    var new_array = array.map(function(item) {
      return false;
    });
    
    console.log(array)
    console.log(new_array)

    0 讨论(0)
提交回复
热议问题