JavaScript复制数组按值 [英] JavaScript Copy Array By Value

查看:53
本文介绍了JavaScript复制数组按值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个数组,并从一个php文件中收到了另一个数组.数据很好,但是当我尝试将一个数组复制到另一个数组时,似乎当我更改arr1时,arr2也会更改.

I have created an array and received another from a php file. The data is fine but when i try to copy one array to another, it seems like when i change arr1 then arr2 is also changed.

它是按我的需要按引用"而不是按值"复制的

It is being copied "by reference" and not "by value" as i need

我也尝试了slice(),但是它不起作用,根本不复制变量,甚至也没有通过引用"的方式.

I also tried slice() butit doesn't work, The variable does not being copied at all, not even "by reference" in that way.

// arr1[0] = "Hey";//this array is coming from another file and the data is fine
var arr2 = [];

arr2[0] = arr1[0];
arr2[0] += "1"; // right now arr1 and arr2 both has "Hey1" in them.

有什么想法吗?谢谢

推荐答案

数组是Javascript中的对象.如您所知,对象是通过引用复制的.您可以在此处查看:什么是最有效的在JavaScript中深度克隆对象的方法?

An array is an object in Javascript. As you might know objects are copied by reference. You could take a look here: What is the most efficient way to deep clone an object in JavaScript?

这篇关于JavaScript复制数组按值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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