...

View Full Version : passing a collection as parameter



Kor
03-18-2005, 04:11 PM
is it possible to pass a whole collection of objects as a parameter?

function bla(){
var col = new Array()
..build the colection
bla2(col);
..continue with the new collection
col[0]... and so on....
}

function bla2(col){
...do something with the collection col which becomes newcol
this.col=newcol;
return this.col;
}

Or it is better to use a new Function() to do that?

liorean
03-18-2005, 04:53 PM
You mean like this?
function one(){
var
aTest=[1,2,3];
aTest.push(4);
two(aTest);
aTest.push(5);
alert('aTest: '+aTest);
}

function two(aOrig){
var
aCopy=[].concat(aOrig).reverse();
aCopy.push(0);
alert('aCopy: '+aCopy);
}

one();
Yes, you can do that. Be aware of the difference between that way of doing it and what happens if you change aCopy=[].concat(aOrig).reverse(); to aCopy=aOrig.reverse();. Arrays are reference types, and copying a reference type doesn't mean the creation of an exact replica, only the copying of a reference to the same object. If you modify the array, you will change the object that references point to, unless you make sure a new object is created.


Also, in JavaScript arrays and collections are considerably different things. Collections are dense, immutable, automatically sized and filled, and doesn't inherit from the Array object. Arrays are sparse (the length may be greater than the number of elements in it), mutable, dynamically sized and manually filled, and do inherit from the Array object. Collections are unlike arrays not natives of the language, but are provided by host implementations of the DOM; e.g. NodeList, NamedNodeMap, HTMLCollection, HTMLOptionsCollection.

Kor
03-18-2005, 05:01 PM
...so that I would better re-create the collection as new Object() ?

liorean
03-18-2005, 05:40 PM
Well, unless you actually want to be editing *the same* array, you need to copy it. A line like aCopy=aOrig.concat([]); does just this. Beware that this makes a shallow copy and not a deep copy. If you want to create a deep copy, see my Array Functionality script.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum