i need to copy one array into another.
doing something like:
myArr1 = myArr2;
will just pass the reference, not copying the data, and further
changes to myArr2 will be reflected in myArr1 – not want i need.
iterating through the whole array and copying value by value works,
but seems a little long winded (maybe it isn’t?)
myArr1[i] = myArr2[i];
was looking around for something like "Array.copy()" – but no luck.
came up with:
myArr1 = myArr2.slice(0);
to actually copy the data, and it works.
just wanted to know what others are doing in this situation and if
there is a preferred method.
those are good tips! I looked through the js core guide, and there simply doesn’t seem to be a method for copying an array to a new one. go figure!
On Jun 9, 2006, at 5:59 PM, pnyboer wrote:
> those are good tips! I looked through the js core guide, and there
> simply doesn’t seem to be a method for copying an array to a new
> one. go figure!
For numerically arrays, just walk one array from zero to array.length
copying one element to the other:
var dest = new Array();
var len = src.length;
dst[i] = src[i];
For associative arrays (i.e. key/value maps, also knows as hash
tables, dictionaries, or hash arrays, and the way in which Andrew
Pask suggested you use arrays to store dynamically named arrays),
people recommend using Object in place of Array. However, if you
aren’t extending Array.prototype (which often is not the case, at
least as used in Max), you can safely use the Array class in this
construct to iterate across an object’s properties. Here’s a
description of why you may wish to use Object in place of Array for
var dest = new Object();
for (i in src)
dst[i] = src[i];
Hope this helps.
Quote: pnyboer wrote on Sat, 10 June 2006 12:59
> those are good tips! I looked through the js core guide, and
> there simply doesn’t seem to be a method for copying an array
> to a new one.
Not as such.
newarray = oldarray.slice(0); or
newarray = oldarray.concat();
Pretty much the standard one-line methods back when I was doing much js web development. Still what I’m using anyway.
As Joshua notes, you could also add a .copy() method extending the Array prototype and bung that in a shared js library, for that matter, though I haven’t felt the need to do anything like this in Max (yet).