如何传递值而不是数组的引用? [英] How do I pass the value instead of the reference of an array?

查看:150
本文介绍了如何传递值而不是数组的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

var a = [];
a.push({"level": 1, "column": 4, "parent": "none", "title": "Node 0", "content": "Parintele suprem", "show": "1"});
var b = a;

a.push({"level": 1, "column": 5, "parent": "none", "title": "Node 1", "content": "Parintele suprem", "show": "1"});

console.log(b);

现在的问题是 b 有确切内容为 a (第二次推送后的内容)。这个建议(纠正我,如果我错了)当我说 b = a 我实际上给了b相同的引用,所以无论我在 a 我在 b 。问题是我需要传递价值。所以我预览 a ,价值在 b

Now the problem is that b has the exact content as a (the content after the second push). This suggest (correct me if I'm wrong) that when I said b = a I actually gave b same reference as a, so whatever I do in a I have in b. The thing is that I need to pass the value. So I have the previews a, value in b.

编辑以使问题更清晰:如何传递值而不是引用?

Edit to make the question more clear: How do I pass the value instead of the reference?

推荐答案

我认为你可以使用它来复制值而不是引用:

I think you can use this to copy the value instead of the reference:

var b = a.slice(0);  

编辑

正如评论所提及的那样它也在这里提到: https://developer.mozilla.org/en/ JavaScript / Reference / Global_Objects / Array / slice

slice 不会改变原始数组,但会返回一个新的一级深度包含从原始数组切片的元素副本的副本。原始数组的元素将复制到新数组中,如下所示:

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:


  • 对于对象引用(而不是实际对象),切片将
    对象引用复制到新数组中。原始数组和新数组
    都引用同一个对象。如果引用的对象发生更改,则更改
    对新的和原始数组都可见。

  • For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

对于字符串和数字(​​不是String和Number对象) ),将
字符串和数字复制到新数组中。对一个数组中的字符串或
数字的更改不会影响另一个数组。

For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

如果是新的element被添加到任一数组,另一个数组不受影响。

If a new element is added to either array, the other array is not affected.

这篇关于如何传递值而不是数组的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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