Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables Google应用程序脚本:新变量保留源变量的引用_Variables_Google Apps Script_Reference_Google Sheets - Fatal编程技术网

Variables Google应用程序脚本:新变量保留源变量的引用

Variables Google应用程序脚本:新变量保留源变量的引用,variables,google-apps-script,reference,google-sheets,Variables,Google Apps Script,Reference,Google Sheets,我们有变量a,我们想创建变量b作为变量的镜像,然后更改其中一个元素 代码 输出 为什么会这样?有没有办法避免这种情况?这涉及到另一个问题: 您可以测试一些建议的解决方案。我已经测试过这个答案: 守则: function h(){ var a=[[1,2,3]]; var b = JSON.parse(JSON.stringify(a)); b[0][0]="test"; Logger.log(b); Logger.log(a); } 结果是 [[test, 2, 3]] [

我们有变量a,我们想创建变量b作为变量的镜像,然后更改其中一个元素

代码

输出


为什么会这样?有没有办法避免这种情况?

这涉及到另一个问题:

您可以测试一些建议的解决方案。我已经测试过这个答案:

守则:

function h(){
  var a=[[1,2,3]];
  var b = JSON.parse(JSON.stringify(a));
  b[0][0]="test";
  Logger.log(b);
  Logger.log(a);
}
结果是

[[test, 2, 3]]
[[1.0, 2.0, 3.0]

看起来,类似javascript的c不执行数组赋值。

您必须在数组b中深度复制值。为此,您可以使用切片方法:

arr2=arr1.5

下面是经过一些修改的代码:

function h(){
var a=[1,2,3];
var b= a.slice();
b[0]="test";
console.log(b);
console.log(a);
}

我利用你的建议做了一个函数,并且在我的项目中到处都能流利地工作。非常感谢。谢谢。但是当我使用数组和对象时,Max的解决方案工作得更好。
[[test, 2, 3]]
[[1.0, 2.0, 3.0]
function h(){
var a=[1,2,3];
var b= a.slice();
b[0]="test";
console.log(b);
console.log(a);
}