Easily deal with mixed object|array parameters
function foo(myMixed)
{
var myArray = [].concat(myMixed);
for(var i = myArray.length; i--; ){
//do your stuff
}
}
This way you can make calls like: foo('bar') or foo(['bar', 'baz']) without checking if the parameter is or not an Array and then converting it. Just one single line of code needed.
Note: I did never say it is efficient, so don't use it for huge arrays.
Note2: This trick isn't mine, I found it somewhere in StackOverflow, but I wanted to share it.
Written by Santiago Aparicio García
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#