I'm working in a function and I need to turn all function's arguments in just one array, even if one argument is an array (or something with a list of values). I need something like array_merge()
in PHP, but keys is not needed, just values that I wanted.
Edit 1:
I'm not looking for how turn object arguments
into Array. I need all values passed as argument into single array. If one or more arguments is an array or object, its values need to be merged to one array. Like the example provided.
For example:
foo('bar', function, [1,2,3], [NodeList], window);
array => ['bar', function, 1, 2, 3, < HTMLElement>, < HTMLElement>, window]
Pay attention on [NodeList], it must turn into HTMLElements.
Done so far:
I've done this function below, but I wanna know if its a better way. Any comments/hints are appreciated.
function toArray(obj) {
var k = Object.keys(obj);
var i = 0, l = k.length;
if (isString(obj) || l == 0 || obj === window) {
return obj;
} else {
var objs = [];
while (i < l) {
objs = objs.concat(toArray(obj[k[i]]));
i++;
}
return objs
}
}
function isString(obj){
return (typeof obj === 'string' || obj instanceof String);
}
Edit 1:
usage:
var arg1 = 'bar',
arg2 = [1,2,3],
arg3 = document.querySelectorAll('body');
foo(arg1, arg2, arg3) {
var myArray = toArray(arguments);
//myArray: ['bar', 1, 2, 3, <body>]
}