Forums > Javascript

arrayfromargs() question

Feb 27 2013 | 8:52 pm

I can’t find anything on this and I was wondering:

calling arrayfromargs(), what is actually returned? If I do
var myAwesomeArray = arrayfromargs(arguments); is "myAwesomeArray" a reference to "arrayfromargs" or is it the equivalent of doing something like:
myAwesomeArray = myOtherNoteQuiteAsAwesomeArray.slice();

Hope someone can clarify or point me to the documentation.

Feb 27 2013 | 9:37 pm

It creates a new Array object, copying the content of arguments. The arguments object is an Array object, though it supports array style indexing. This is a convenience function so that people who want to call Array object methods can do so, without having to do that copying to an actual Array object in JS.

Feb 27 2013 | 10:24 pm

If I understand correctly that means that:

arrayfromargs() creates a new array (by copying, not reference) of "arguments". this means when I assign it to something like newArray[0] = arrayfromargs(arguments); newArray[0] is now referencing the array created by arrayfromargs(). If I send another list to my function, a new array is created and, let’s say put in newArray[1], but since everything is done by copying already, [0] and [1] are pointing to two different arrays in memory.

Am I understanding this correctly?

Feb 27 2013 | 11:02 pm

Yes. Please let us know if you experience otherwise.

However, please note that in JS array copying is not "deep" so if you have an array of arrays, only the top layer is distinct. Hopefully that doesn’t lead to more confusion, but it’s a general JS characteristic and plenty of more information on the subject online. e.g. quick google on "array deep copy in javascript"

Feb 28 2013 | 6:40 pm


Jan 29 2014 | 10:10 am

eek, so just realised that calling this as a matter of course imediately doubles gc work on every call…. glad i found this

Viewing 6 posts - 1 through 6 (of 6 total)

Forums > Javascript