克隆数组上的Javascript array.push修改原始数组 [英] Javascript array.push on clone array modify original array

查看:45
本文介绍了克隆数组上的Javascript array.push修改原始数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个非常奇怪的问题(对我来说)

I found a really weird (for me) problem

我有这个全局变量ARRAY

I have this global variable ARRAY

var A = [1,2,3,4]

然后在函数中,我创建了本地变量,并为其分配了先前的全局变量

then inside a function, I made local var and assign previous global var to it

function someFunc() {
     var X = A;
}

然后我制作了另一个本地Var,并为其分配了第一个本地var的值

I then made another local Var and assign it with the first local var's value

var Y = X;

然后我将一个新值推到Y

I then push a new value to Y

Y.push(6);

但是,新值(6)不仅被推到Y,而且被推到2个原始数组(X和A).发生了什么?它不是应该只改变Y吗?

but the, the new value (6) didn't only pushed to Y, but also to the 2 original array (X and A). What happened? Doesn't it supposed to only change Y?

请帮助,谢谢.

这是我的完整代码:

var A = [1,2,3,4];


function someFunc(){
    var X = A;
    var Y = X;
    Y.push(6);
    console.log(A);
    console.log(X);
    console.log(Y);
}

$("#test").click(function(){
    someFunc();
});

如您所见,它是通过单击ID为#test的元素触发的.

as you can see, it is triggered by clicking on element with id #test.

所有三个console.log,甚至认为代表不同的变量,它都返回相同的结果,上面带有6的ARRAY

All three console.log, even thought represent different variable, it return the same result, ARRAY with 6 on it

编辑.是的,对此存在类似的问题,但是即使问题相似且解决方案相同,但最初的理解是有什么不同.在我的问题中,我最初问为什么",因为我不知道那些变量实际上是引用"到同一数组而不是分配",所以我不知道是否应该搜索如何分配而不是引用,因为我以为使用 = 意味着分配,对不起

Edit. Yes there is a similar question to this, but even though the problem is similar and the solution is identical, but the initial understanding is what different. In my question, I initially asked "Why", because I am not aware of those variable actually 'refer' to same array instead of 'assigning', so I have no idea if I should search for how to assign instead of refer, since I assumed that using = means assigning, sorry

推荐答案

发生的事情是您没有复制只是引用它的数组.您可以使用 slice 创建它的副本:

What happens is that you do not copy the array you just reference it. You can use the method slice to create a copy of it:

var X = A.slice();

请注意,您只能对原始值使用此方法.如果您需要处理对象如何处理,请选中此复选框在Javascript中克隆对象数组?

Do mind that you can use this approach only with primitive values. Check this if you need to deal with objects How do you clone an Array of Objects in Javascript?

这篇关于克隆数组上的Javascript array.push修改原始数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆