Reputation: 111
I found this question but unfortunately it was just closed. There are many good answers but I wonder why no one suggested the following solution:
a = a.concat(b)
The author said he don't wanted to have an new array but extend the array a.
Upvotes: 0
Views: 93
Reputation: 48247
Setting the local variable to the value does not necessarily mean that will propagate to everywhere that variable is referenced. Take the example:
var foo = (function() {
var bar = [1, 2, 3, 4, 5];
return {
get: function() {
return bar;
},
show: function() {
$("html").append("<div>" + bar.length + "</div>");
}
};
})();
var a = foo.get();
foo.show();
a = foo.get();
a = a.concat([6, 7]);
foo.show();
a = foo.get();
a.push([6, 7]);
foo.show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
The second call to show
prints "5", because bar
was not modified by a = a.concat
. Because a
and bar
are references, when you set a
to the return value of bar.concat
, a copy of bar
is made and assigned to a
. The location bar
references does not change, nor do the contents of the array previously known as bar
.
When one reference is reassigned, that does not propagate to every place referencing bar
(if it did, copying would be nigh-impossible).
Getting into which array methods are the most helpful in this situation, you probably push
or splice
. It depends on the exact use (appending or inserting at a particular index, removing existing elements, one at a time or from another array).
Splice can do some interesting things within an array, and has the fun property of returning elements that are removed. It can both insert and replace elements, depending on the parameters provided.
Push does just that, appending elements to the end of the array as if it were a list. If you have another array, it.push.apply(other)
is a handy way to combine them.
If you have access to Underscore.js, many of the collection methods in there can be useful. They typically return a new array, but offer such functionality as flatten
and union
.
Upvotes: 1