I am working with a very poorly documented javascript API, and need to write callback functions where the arguments have not been documented. As an opening step, I need to inspect what gets passed in. If I know that there's only one input I can set the callback function to be
function( stuff ){
console.log(stuff);
}
and work from there. Is there an elegant way to inspect inputs when I don't know how many there are? I could do something like
function(a,b,c,d,e,f){
console.log(a)
console.log(b) // is this undefined?
console.log(c) // how about now?
....
console.log(f) // if this isn't undefined I need to do it again with more args
}
and it will work fine, but it's pretty ugly. Is there a simpler way to find out how many argumetns have been passed to a function?
Loop the arguments object:
function f(){
for(var prop in arguments) {
console.log(arguments[prop]);
}
}
f(1); // logs 1
f(1, 2); // logs 1, then 2
As arguments is an array-like object, you can also iterate it with a regular for loop, based on its length property:
for(var i=0; i<arguments.length; i++) {
console.log(arguments[i]);
}
It looks like you are after arguments, which gives you an array of the arguments passed to the current function:
var f = function() {
console.log(arguments);
}
f(1, '2');
f(1, 2, 3, 4, 5);
(Fiddle)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With