我在 Google Sheet 中的应用程序脚本遇到以下问题。
我想在表格的基础上制作工作表中一行的不同副本。我想做一些类似的事情
input1=[[1,2,"a"]];
input2=[[4,5,"b"],[7,8,"c"]];
function (input1,input2) {
\\ input# is a row, ie. an array with single element, which is another array
\\ The rows input# represent are of equal length
out=[];
copy1=input1[0];//copy1 is a reference to input1[0]
copy2=input1[0];//copy2 is a reference to input1[0]
for (i=0;i<input1.length,i++) {//input1.length is 1
copy1[i]+=input2[0][i];
copy2[i]+=input2[1][i];
}
out.push(copy1,copy2);//copy1=[5,2,a] copy2=[8,2,a]
return out
}
我希望
out
看起来像
out=[[5,7,"ab"],[8,10,"ac"]];//[[5,2,a],[8,2,a]]
但事实并非如此。输出看起来就像每当我修改
copy1
或 copy2
时,都是 input1
本身被修改。
这里出了什么问题?如何创建一个新的数组变量,将其值指定为等于现有数组并修改新数组而不更改旧数组?输入数组的元素(元素的)由混合数字和字符串组成是否可以?
试试这个方法:
function myFunction(input1,input2)
{
var input1=[[1,2,"a"]];
var input2=[[4,5,"b"],[7,8,"c"]];
var out=[];
var copy1=input1[0].slice();//slice returns a copy of the array
var copy2=input1[0].slice();
for (var i=0;i<input1[0].length;i++)//looping through all of elements of input1[0];
{
copy1[i]+=input2[0][i];
copy2[i]+=input2[1][i];
}
out.push(copy1,copy2);
Logger.log(out);//out=[[5,7,"ab"],[8,10,"ac"]];
}
有关切片的更多信息,请查看此处。
这是一个好问题。我自己也曾为此挣扎过几次。
//-- Append our new needs to needs without changing needs
var needs = ["FunctionName", "Source", "User"]
var newNeeds = needs.slice(0,needs.length) // Creates a new Exact copy duplicate of an array
newNeeds.push("Code")
Logger.log(needs) // Expect ["FunctionName", "Source", "User"] No Change
Logger.log(newNeeds) // Expect ["FunctionName", "Source", "User","Code"] Added "Code"
debugger