How to print argument list in javascript?

Is there a way to print the argument list in whole or in part in JavaScript?

Example: from the function my_assert(a!=b) I would like to print a!=b or even 2!=3 for a specific function call.

+7
source share
5 answers

You can not. a!=b is executed first, and only the result of this ( true or false ) is assigned to your function, so you have no way to return a!=b or 2!=3 .

+3
source
  console.log (arguments) 

will output the arguments of the function, but in your case, your whole function sees a logical value, because a != b will be evaluated first, and only the result is passed as a parameter in the function call.

+2
source

umm ... here, I will google this for you :) http://www.seifi.org/javascript/javascript-arguments.html

As some others pointed out, passing the test (a! = B) will only result in your boolean value (true | false) as your argument. But if you call myAssert (a, b), you can then evaluate the arguments and check their equality, as well as print their values, following the recommendations in the inserted link.

+1
source

You cannot do this. If you have the following line:

 my_assert(a!=b); 

The expression a!=b will be evaluated first, and its result will be passed to my_assert .

Assuming your function my_assert() used specifically for your own testing, and you can control how it works and what you go into it, you can do something like this:

 my_assert(a!=b, "a!=b"); 

Ie, pass an additional parameter to the function with a string representation of what is being tested. Obviously, this will not stop you from accidentally saying my_assert(a!=b, "a==b"); and this is awkward, but I can't think of another way to do it.

0
source

Here you go:

 my_assert = (test) -> str = my_assert.caller.toString() match = /return my_assert\((.*)\)/.exec str console.log match[1], test a = '1' b = '2' do -> my_assert(a!=b) do -> my_assert(b!=a) > a !== b true > b !== a true 

http://jsfiddle.net/m7qRN/

The only caveat is that you must call your my_assert calls separate anonymous functions in order to be able to reliably get the source code of the confirmation call.

In CoffeeScript, it's not so bad using the notation do -> .

In JS, this is: (function(){my_assert(a!=b)})(); .

You can pass the test as a function:

my_assert -> a!=b

my_assert(function(){a!=b});

0
source

All Articles