如何通过 google 脚本中的映射函数更改二维数组中的一列?

How to change one column in 2d array by mapping function in google scripts?

我有一个数组,它是通过 .getValues() 方法从电子表格中获得的:

var arr = [
[12, 123euro, 13],
[345, 432euro, 293],
]

我想通过这样的映射删除 'eur':

var newarr = arr.map(row => row[1].replace('euro',''))

但这给了我:

[123, 432]

将行重写为:

newarr = arr.map(row => [row[0], row[1].replace('euro',''), row[2])

给了我想要的 newarr:

var arr = [
[12, 123euro, 13],
[345, 432euro, 293],
]

第一次尝试就预料到了这个结果。我错过了什么?

Array.prototype.map() 期望每次迭代有一个 return 值,该值分配给调用它的数组中该迭代的索引。

您的第一次尝试 arr.map(row => row[1].replace('euro','')) return您的 .replace() 调用的 return 值,它是一个字符串,并替换整个迭代的 row有了它。

相反,您想将该 returned 值分配回 row[1],然后 return 整行。 (这里使用了comma operator and converting the returned string to an integer using a unary plus(+))。

arr.map(row => (row[1] = +row[1].replace('euro', ''), row))

应该注意的是,以这种方式改变 row 数组也会改变原始数组。为避免这种情况,您需要使用 slice() or by using spread syntax 进行复制(或者像您在工作示例中所做的那样构建一个全新的数组)。

var arr = [
  [12, '123euro', 13],
  [345, '432euro', 293],
];

var newarr = arr.map(row => {
  const newRow = [...row];
  newRow[1] = +newRow[1].replace('euro', '');
  return newRow;
})

console.log(newarr);

function myfunc() {
  var arr = [
    [12, '123euro', 13],
    [345, '432euro', 293]
  ];
  let arr1 = arr.map((r) => {
    return [r[0], r[1].replace(/euro/g, ''), r[2]];
  });
  Logger.log(arr1);
}

Execution log
4:07:32 PM  Notice  Execution started
4:07:32 PM  Info    [[12.0, 123, 13.0], [345.0, 432, 293.0]]
4:07:32 PM  Notice  Execution completed