开发者

How to retain array in javascript?

Here's some code that has two arrays(np and op), one a copy of the other

However, when I modify the copy, the original 开发者_运维百科is also modified! take a look:

<script type="text/javascript">
var op=new Array(0, 0);
var np=op;
np[1]=2;
document.write(op+"<br>")
document.write(np)
</script>

Is there any way to retain the original and modify the copy?


Some of the built in Array functions will actually create a copy for you. One such is slice.

For example:

var op=new Array(0, 0);
var np= op.slice(0);
np[1]=2;
document.write(op+"<br>")
document.write(np)

Reference http://my.opera.com/GreyWyvern/blog/show.dml/1725165


You never made a copy of the array. You simply assigned the array to another variable. This does not copy in Javascript. In your example there is only one array with two variables by which you can access it. There is no built-in way to copy arrays in Javascript so you will need to write your own function to do it.

Take a look at this StackOverflow question for a hint on how to actually implement the copying of the elements in the array.


What you are doing is not creating a copy of the array, it's only creating a copy of the reference to the array, so you get two references to the same array object.

This is how you can create an actual copy of the array:

var np = op.concat();

The concat method creates a new array that is a copy of the array with any additional items added. If you don't specify any additional items you just get a copy of the array.


Array.prototype.copy = function() {
    return this.slice(0, this.length);
  }

Then


var op=new Array(0, 0);
var np=op.copy();
np[1]=2;
document.write(op+"<br>")
document.write(np)


You should clone the second array instead of copying it.

--- Update

If you assign an object to a variable, only the reference is copied (that means, they both point to the same data). For having an independent copy of this object you need to clone it. And there are several ways how to this, for example here is the way of cloning object using jQuery.


You can just use the native slice method which returns a copy of the array:

var np = op.slice(0,op.length);

The second parameter should be optional, but in IE I believe it is required.

Your code, complete with the change:

var op=new Array(0, 0);
var np=op.slice(0,op.length);
np[1]=2;
document.write(op+"<br>")
document.write(np)


To create a new array you might want to consider:

   var op = [];


To copy an array:

var np=op.slice();

or

var np=op.concat();

concat is faster, while slice takes up one less character. Some people alias "slice" or "concat" as "copy" so that it's more obvious that you're making a copy.

No need for parameters in either case. Parameters in the slice will just make the code larger and slower.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜