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

And*_*son 1 javascript arrays mapping multidimensional-array google-apps-script

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

var arr = [
[12, 123euro, 13],
[345, 432euro, 293],
]
Run Code Online (Sandbox Code Playgroud)

我想通过这样的映射来删除“eur”:

var newarr = arr.map(row => row[1].replace('euro',''))
Run Code Online (Sandbox Code Playgroud)

但这给了我:

[123, 432]
Run Code Online (Sandbox Code Playgroud)

将这一行重写为:

newarr = arr.map(row => [row[0], row[1].replace('euro',''), row[2])
Run Code Online (Sandbox Code Playgroud)

给我想要的 newarr:

var arr = [
[12, 123euro, 13],
[345, 432euro, 293],
]
Run Code Online (Sandbox Code Playgroud)

我从第一次尝试就期待这个结果。我缺少什么?

pil*_*ard 5

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

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

相反,您希望将返回值分配回row[1]并返回整行。(这里使用 acomma operator并使用 a 将返回的字符串转换为整数unary plus(+))。

arr.map(row => (row[1] = +row[1].replace('euro', ''), row))
Run Code Online (Sandbox Code Playgroud)

应该注意的是,row以这种方式改变数组也会改变原始数组。为了避免这种情况,您需要使用slice()扩展语法(或者像在工作示例中那样构建一个全新的数组)来制作副本。

arr.map(row => (row[1] = +row[1].replace('euro', ''), row))
Run Code Online (Sandbox Code Playgroud)