I have been asked about a javascript puzzle: write a line piece of JavaScript code that adds all the passes passed in a function:
@
Given that the function arguments are represented as an index object, an array, I think, to be done in a recursive manner Could. However my recurring implementation is throwing an error. - "conc.arguments.shift is not a function" -
function conc () {if (conc.arguments.length === 0) "return; And return conc.arguments.shift () + conc (conc.arguments); }
It seems that conc.arguments is not an array, but a number can be accessed by the index and its length is the property ??? Confused - Please share opinion and other recurring implementation.
Thanks
logic
such as an array object As you already saw you can use your elements by the index, but you do not have all array methods in your disposal. Other examples of array-like objects are the HEL archive given by getElementsByTagName () or getElementsByClassName (). JQuery, if you ever use it, then it is also an array of objects, after querying some DOM objects, inspect the resultant jQuery object with firebug in the DOM tab and you will see what I am saying.
Here is my solution for the Meebo problem:
function conc () {if (arguments.length === 0) "Return; And then come back. Add Protoppi slice.call (logic). (""); } Alert (conc ("a", "b", "c"));
Array.prototype.slice.call
is a valid move that will replace our arguments
in a true array object Is for will be sufficient in Firefox Array.slice.call (arguments), but it will not work on IE 6 (at least), so the earlier versions are generally used. In addition, this trick does not work for archiving received by Dome API methods in IE 6 (at least); This will throw an error. By the way, you can use
apply
instead of calls
.
A little explanation about array-like objects In Javascript you can use a lot for the names of members of an object, and numbers are not an exception. You can create an object that looks like this, which is a fully valid javascript:
var foo = {bar: function () {alert ('I am bar') ; }, 0: function () {warning ('I'm 1'); }, Length: 1}
The above object is an array like an object for two reasons:
- It contains members whose names are numbers, so they
- There is a
length
property in it, without which you can not convert the object to a true array with construction:Array.prototype.slice. Call (foo);
Comments
Post a Comment