Recently, as I was slowly working my way through Rebecca Murphy's excellent js-assessment test suite, I ran into a problem that was quite vexing. I was creating a function that was to take an arbitrary number of arguments and combine them with an existing array. I thought that this would be as trivial as using the concat method on the existing array and passing in the arguments object. However, as you can see below, it didn't work.
JS Bin
For a while I thought that I must be using the concat method incorrectly. I tested it using the terminal again and again with no problems. Finally I recalled a recent issue from A Drip of JavaScript that talked about the arguments object. I remembered that Joshua said that the arguments object "isn't exactly an array, [but rather an] object that acts like an array." This means that you can's use it exactly like an array. An easy fix for the situation was to bind a call to the slice method on an empty array to the arguments object which converts it to a true array object like so:
JS Bin
Hopefully this will save you some time in the future and also convince you that you should really subscribe to A Drip of JavaScript. Each week there is a great article that is short enough that I can read it without feeling like I have to dedicate a bunch of time and yet in depth enough to give me some useful knowledge.
No comments:
Post a Comment