【问题标题】:How to change data in array, then paste them back changed如何更改数组中的数据,然后将它们粘贴回更改
【发布时间】:2019-08-29 10:08:48
【问题描述】:

所以我有数组 ["test1#1", "test2#1", "test3#1", "test4#1", "test5#0"] 我想替换所有#1,然后将它们粘贴回同一数组中的同一位置。

JS:

function catData(array) {
  let result = array.map(a => a.TERM + "#" + a.PRIORITY);
  result.forEach(d => {
    if (d.includes("#1")) {
      let less = d.replace("#1", "");
      console.log(less);
    }
  });
  console.log(result);
}

【问题讨论】:

    标签: javascript


    【解决方案1】:
    function catData(array) {
      let result = array.map(a => a.TERM + "#" + a.PRIORITY);
      result.forEach((d, i) => {
        result[i] = result[i].replace("#1", "") // can replace in place
      });
      console.log(result);
    }
    

    【讨论】:

      【解决方案2】:

      只需使用 map() 即可:

      ["test1#1", "test2#1", "test3#1", "test4#1", "test5#0"].map(item => item.replace("#1", "#5"))
      

      注意:它会生成一个新的数组,并保持原来的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-30
        • 1970-01-01
        相关资源
        最近更新 更多