LNA
LNA

Reputation: 1447

How do I console log each of the arguments I pass into this test function?

Here is a demo.

I'm trying to output a, b, and c consecutively. But console.log() is just giving me back the first value.

function test(values){ 
    console.log(values);
} 

test('a', 'b', 'c'); 

Upvotes: 0

Views: 1659

Answers (7)

wonu wns
wonu wns

Reputation: 3608

It is because you have a function which only accepts a single argument that is values. If you want to pass a, b, and c, change your function to accept three values:

function test(val1, val2, val3){
    console.log(val1 + val2 + val3);
} 

or store a, b, and c on an array. In your code, the number of arguments don't match.

Upvotes: 0

Just code
Just code

Reputation: 13791

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

test('a', 'b', 'c'); 

You are creating a function so arguments to that function should be match when you are calling this function. So if you want three parameters, then just add three parameters to your function.

Upvotes: 0

SarathSprakash
SarathSprakash

Reputation: 4624

Your function has only one parameter and you are giving it three parameters. This won't work like an array - you have to modify the code:

function test(values){ 
    for( var i=0; i<values.length; i++)
    alert(values[i]);
} 

test(['a', 'b', 'c']); 

Upvotes: 0

Salvador Dali
Salvador Dali

Reputation: 222461

The quick answer is to use

function a( b, c, d){
 console.log(arguments);
}

a(5, 8, 9, 9, 9) will output

[5, 8, 9, 9, 9]

BTW, take a loot at other functions except of console.log()

  • console.log( myvar, "Logged!");
  • console.info( myvar, "Logged!");
  • console.warn( myvar, "Logged!"); console.debug(myvar, "Logged!");
  • console.error(myvar, "Logged!");

Upvotes: 0

Colin Brock
Colin Brock

Reputation: 21565

You want arguments:

console.log( arguments );

Keep in mind though that arguments, while looking like an array, is actually an object. You can convert it to an array, if needed, like this:

var args = Array.prototype.slice.call(arguments);

Alternately, as alex pointed out in the comments, with jQuery you can simply do:

$.makeArray(arguments)

Upvotes: 4

Pastor Bones
Pastor Bones

Reputation: 7351

You can use the javascript variable arguments

function blah() {
   console.log(arguments);
}

blah(1, 2); // [1, 2]
blah([1, 2], [3]); // [[1,2], [3]]
blah(1, [2, 3], "string"); // [1, [2, 3], "string"]

Upvotes: 0

Use arguments

Working Fiddle

function test(values) {
    var i;
    for (i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}

test('a', 'b', 'c');

Upvotes: 2

Related Questions