Sunday, April 25, 2010

Solution to my last post.

In my last post I was trying to create a function that receives a multidimensional array inside parameters like (2, 4, 5) but with an infinite amount that could be passed in, and I was having problems with pass by reference, instead of pass by value.

I fixed it, and came up with a very simple solution:

p.ArrayList = function() {
var createArrayList = function(args){
var array = new Array();
for (var i = 0; i < args[0]; i++){
array[i] = (args.length !== 1 ? createArrayList(args.slice(1)) : 0 );
}

return array;
};
return createArrayList(Array.prototype.slice.call(arguments));
};

I came across the problem of arguments only acting like an array, but not having access to many array like functions, like slice(). Solution.

Array.prototype.slice.call(arguments)

Array.prototype.slice gets the slice method from the Array object.
call() allows you to call an object's function from the context of another object.
and the slice method would be called, using the function definition attached to Array, like it was part of arguments, and just return a copy of the array's values, as an array. :D

No comments:

Post a Comment