js 复制数组后更改原始数组,新数组值也被改变 求解

bai2hao3 2012-06-13 11:39:39
代码如下

var astrPaymentJsons = maobjCurrent[2].slice(0);
////////////////////////①///////////////////////////
if (!VerifyReceiptAmount()) {
return false;
}
////////////////////////②///////////////////////////

于是在①的时候和②的时候astrPaymentJsons中的值不一样了,求解!!!!

注: maobjCurrent[2]为全局变量
VerifyReceiptAmount方法中改变了maobjCurrent[2]的值
...全文
770 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
bai2hao3 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]
可以肯定是代码的问题,用Firebug进行断点调试吧,先找到是哪一行代码修改了astrPaymentJsons数组的值。
[/Quote]
我查询了页面上的astrPaymentJsons 只留下了var astrPaymentJsons = maobjCurrent[2].slice(0);
然后在上面说的///①////,////②////的地方写了alert(astrPaymentJsons[0]);
调试的时候经过VerifyReceiptAmount方法值就被改变了
乌镇程序员 2012-06-13
  • 打赏
  • 举报
回复
可以肯定是代码的问题,用Firebug进行断点调试吧,先找到是哪一行代码修改了astrPaymentJsons数组的值。
bai2hao3 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
怎么可能呢。。除非你在VerifyReceiptAmount()中修改了astrPaymentJsons的值,不然的话就不会改变。

JScript code
var ar1 = [1,2,3];
var ar2 = ar1.slice(0);
ar1[0] = 'A';
alert(ar2); //1,2,3
[/Quote]

是啊 我也感觉很奇怪的,但是上面的astrPaymentJsons是我新定义的啊 我改成“AAABB”这样的都不行

var marray1 = new Array("1", "2", "3");

function clone1() {

var array2 = marray1.slice(0);
alert(array2);
if (!VerifyReceiptAmount()) {
return false;
}
alert(array2);
}

function VerifyReceiptAmount() {
marray1[0] = "2";
return true;
}


上面这个是我测试用的 也是成功的, 但是代码里的就是不行.....
乌镇程序员 2012-06-13
  • 打赏
  • 举报
回复
怎么可能呢。。除非你在VerifyReceiptAmount()中修改了astrPaymentJsons的值,不然的话就不会改变。
var ar1 = [1,2,3];
var ar2 = ar1.slice(0);
ar1[0] = 'A';
alert(ar2); //1,2,3
bai2hao3 2012-06-13
  • 打赏
  • 举报
回复
感谢T5500的帮助
下面贴出代码

function clone(jsonObj) { 
   var buf; 
   if (jsonObj instanceof Array) { 
     buf = []; 
     var i = jsonObj.length; 
     while (i--) { 
       buf[i] = clone(jsonObj[i]); 
     } 
     return buf; 
   }else  if (jsonObj instanceof Object){ 
     buf = {}; 
     for ( var k in jsonObj) { 
       buf[k] = clone(jsonObj[k]); 
     } 
     return buf; 
   }else { 
     return jsonObj; 
   } 
} 
乌镇程序员 2012-06-13
  • 打赏
  • 举报
回复
原来原始数据是个JSON数组啊。。那就不能使用普通数组的slice()方法来复制了,因为数组保存的是对对象的引用。自己google一下:JSON 深度复制

bai2hao3 2012-06-13
  • 打赏
  • 举报
回复

maobjCurrent[2][intIndex]["ReceiptAmount"] = (floatOrderTotal - floatPartAmountPaid).toString() ;
return true;

监视到这一步执行后
astrPaymentJsons[1].ReceiptAmount就被改了..... 哪位高手知道 求解啊

87,914

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧