我正在尝试使用Google App脚本中的拼接来提取2D数组的子集。 A是从中创建两个数组info []和ttdata []的输入数组。以下是代码:
function SpliceTest()
{
var A = [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],
["","","","1","",""],["","","","","2",""]]
Logger.log(A)
var spliced = SpliceData(A)
Logger.log(A)
}
function SpliceData(data)
{
var info = []
var ttdata = []
for(var j = 0; j < 2; j++)
{
info[j] = data[j].splice(4, 2)
}
for(var j = 2; j < data.length; j++)
{
ttdata[j-2] = data[j].splice(0, 4)
}
return [info, ttdata]
}
问题是,执行spliceData子例程会修改我无法理解的输入数组A。
下面是执行SpliceData子例程之前和之后的A值。
[19-01-25 11:28:05:493 CET] [[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [, , , 1, , ], [, , , , 2, ]]
[19-01-25 11:28:05:494 CET] [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0], [5.0, 6.0], [, ], [2, ]]
答案 0 :(得分:1)
在这里,正如特豪霍(Tehhowch)在评论中提到的那样,您需要slice()
而不是splice()
此外,如果您阅读了文档,您会发现拼接会修改原始数组,而slice会对其进行浅表复制。
function SpliceTest()
{
var Logger = console
var A = [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],
["","","","1","",""],["","","","","2",""]]
var spliced = SpliceData(A)
Logger.log("Spliced Array:")
Logger.log(spliced)
Logger.log("Original Array A:")
Logger.log(A)
}
function SpliceData(data)
{
var info = []
var ttdata = []
for(var j = 0; j < 2; j++)
{
info[j] = data[j].slice(4)
}
for(var j = 2; j < data.length; j++)
{
ttdata[j-2] = data[j].slice(0, 4)
}
return [info, ttdata]
}
SpliceTest()
注意:我修改了代码,即var Logger = console
,以便可以在此处作为代码段运行!