【问题标题】:How to create a true new copy of an array in App Script for Google Sheet?如何在 Google Sheet 的 App Script 中创建一个真正的新数组副本?
【发布时间】:2025-12-18 22:55:01
【问题描述】:

我在 Google 表格中遇到以下应用脚本问题。

我想在表格的基础上制作工作表中一行的不同副本。我想做类似的事情

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]]

但事实并非如此。输出看起来就像每当我修改 copy1copy2 时,修改的是 input1 本身。

这里有什么问题?如何创建一个新的数组变量,将其值分配为等于现有数组并修改新数组而不更改旧数组?输入数组的元素(元素)由混合的数字和字符串组成是否可以?

【问题讨论】:

    标签: arrays variables google-apps-script google-sheets


    【解决方案1】:

    使用 Slice() 返回一个数组的副本

    试试这个方法:

    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"]];
    }
    

    有关切片的更多信息,请查看here

    这是个好问题。我自己也挣扎过几次。

    【讨论】: