I came across a javascript puzzle asking: Write a one-line piece of JavaScript code that concatenates all strings passed into a function:
function concatenate(/*any number of strings*/) { var string = /*your one line here*/ return string; }
@ meebo
Seeing that the function arguments are represented as an indexed object MAYBE an array, i thought can be done in a recursive way. However my recursive implementation is throwing an error. –"conc.arguments.shift is not a function" —
function conc(){ if (conc.arguments.length === 0) return ''; else return conc.arguments.shift() + conc(conc.arguments); }
it seems as though conc.arguments is not an array, but can be accessed by a number index and has a length property??? confusing — please share opinions and other recursive implementations.
Thanks
argumentsis said to be an Array-like object. As you already saw you may access its elements by index, but you don’t have all the Array methods at your disposal. Other examples of Array-like objects are HTML collections returned by getElementsByTagName() or getElementsByClassName(). jQuery, if you’ve ever used it, is also an Array-like object. After querying some DOM objects, inspect the resulting jQuery object with Firebug in the DOM tab and you’ll see what I mean.Here’s my solution for the Meebo problem:
Array.prototype.slice.call(arguments)is a nice trick to transform ourargumentsinto a veritable Array object. In FirefoxArray.slice.call(arguments)would suffice, but it won’t work in IE6 (at least), so the former version is what is usually used. Also, this trick doesn’t work for collection returned by DOM API methods in IE6 (at least); it will throw an Error. By the way, instead ofcallone could useapply.A little explanation about Array-like objects. In JavaScript you may use pretty much anything to name the members of an object, and numbers are not an exception. So you may construct an object that looks like this, which is perfectly valid JavaScript:
The above object is an Array-like object for two reasons:
lengthproperty, without which you cannot transform the object into a veritable Array with the construct:Array.prototype.slice.call(Foo);The arguments object of a Function object is pretty much like the Foo object, only that it has its special purpose.