2

Possible Duplicate:
Inspect the names/values of arguments in the definition/execution of a JavaScript function

When debugging javascript, I often have code like this:

function doSomething(a,b,c) {
    console.log(a,b,c);

    //function contents here
    //...
}

This results in a line in the console like this:

0.0010719847172334315 0.002392010391772366 -2.764548758273147e-7

Which is hard to read. I want to have output like this:

a: 0.0010719847172334315, b: 0.002392010391772366, c: -2.764548758273147e-7

Is this possible to do? I don't think it is possible to do in many languages. However, I don't know javascript very well, and it seems like a language where it is possible to do clever things like this.

Community
  • 1
  • 1
Oliver
  • 11,297
  • 18
  • 71
  • 121
  • Many debuggers give you even more power then that if you set a brakpoint in that spot instead. I'd prefer using them instead of littering the code under console.logs – hugomg Nov 28 '11 at 17:11

1 Answers1

4

You can do something like this by taking in a parameter object and iterating over it:

function doSomething(options) {
    var i, parameterString = [];
    for (i in options) {
        if (!options.hasOwnProperty(i)) continue;
        parameterString.push(i + ': ' + options[i]);
    }
    console.log(parameterString.join(', '));

    //function contents here
    //...
}

// Invoke like this:
var result = doSomething({a: 'a', b: 'b', c: 'c'});

Note that most of the cruft is due to you wanting to log the parameters on one line; in some other cases (such as logging one per line), you can simply call console.log on each of the individual strings and not bother with the array or the string join.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • I'm not sure how easy it is to do what you want with positional arguments, though. Sorry :-( – Platinum Azure Nov 28 '11 at 16:10
  • @Matt: I meant with the function declared like: `function doSomething(a, b, c)`; there seems to be no way to get the names of those variables because those are really positional arguments. If you want keyword arguments, you need an object; in that case, both your object and mine will work equally well in my function. – Platinum Azure Nov 28 '11 at 16:30
  • @PlatinumAzure Thanks for your answer. I guess this is the best kind of solution we can manage. It's not ideal though - my main motivation for this question was to get a function to quickly write some readable diagnostics for certain sets of variables, without having to write something like `console.log("username:" + usr + " ,first name: " + frstName);` or similar. having a function which takes an object only helps a little. – Oliver Nov 28 '11 at 17:14