代码之家  ›  专栏  ›  技术社区  ›  MeltingDog

JavaScript:可以用forEach更新数组项的值吗?

  •  0
  • MeltingDog  · 技术社区  · 6 年前

    我想循环遍历一个数字数组,如果其中任何一个数字是一位数,则添加一个 0 在它之前 1 变成 01

    我可以用一个 for 但我想知道我是否可以 forEach

    有人知道这能不能做到吗?

    我的代码:

      numArr.forEach(function(item) {
        if (item < 10) {
          item = '0' + item; // How do I update this value in array?
        }
      });
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Mamun    6 年前

    你通过了 作为事件处理函数的第二个参数并使用 要修改数组中的项:

    numArr.forEach(function(item, i) {
      if (item < 10) {
        numArr[i] = '0' + item; // How do I update this value in array?
      }
    });
    

    你也可以使用 map() :

    numArr = numArr.map(function(item, i) =>  {
      if (item < 10) {
        item = '0' + item; // How do I update this value in array?
      }
      return item;
    });
    
        2
  •  2
  •   Nina Scholz    6 年前

    你可以用 Array#map

    var numArr = [1, 2, 3, 10],
        zeroes = numArr.map(v => v.toString().padStart(2, '0'));
    
    console.log(zeroes);
        3
  •  2
  •   jo_va    6 年前

    如果要就地修改数组,则 Array.forEach() 这是一种方法,您必须使用索引来实现这一点,这是回调的第二个参数。

    但是,如果要生成新数组,我建议使用 Array.map()

    const numArr = [-1, 0, 1, 2, 3, 10, 11, 12, 100, 3.14];
    
    const prefix = x => {
      const s = `0${x.toString().replace('-', '')}`;
      return s.split('.')[0].length >= 3 ? `${x}` : `${x < 0 ? '-' : ''}${s}`;
    }
    
    const result = numArr.map(prefix);
    
    numArr.forEach((x, i) => numArr[i] = prefix(x));
    
    console.log(result);
    console.log(numArr);
        4
  •  2
  •   Vikas    6 年前

    你可以用 map

    var numArr = [1, 2, 3,10,11];
    numArr = numArr.map(function(item) {
       if (item < 10) {
          return item = '0' + item;;
        }
      return item.toString() ;
    });
    console.log(numArr);

    还有一个操作是 forEach 有两个参数(第二个参数是索引),

    var numArr = [1, 2, 3,10,11];
    numArr.forEach(function(item,index) {
       if (item < 10) {
          numArr[index] = '0' + item;
        }
      
    });
    
    console.log(numArr);
        5
  •  1
  •   Saurabh Yadav    6 年前

    你可以用 padStart map

    var cont = [1, 2, 3, 4, 5, 6, 7, 10, 11, 12];
    var result = cont.map((o)=>{ return o.toString().padStart('2', 0);});
    
    console.log(result);