Skip to content Skip to sidebar Skip to footer

How To Make Function Return More Than One Value

This is my code: var Evalcard = function(number) { if (number == 1) { this.name = 'Ace'; this.value = 11; } else if (number == 11) { this.name

Solution 1:

In this case, you probably want to return either an array or an object literal:

return { name: this.name, value: this.value };
// later: EvalCard(...).name; EvalCard(...).number;return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];

Solution 2:

How about this:

return [this.name, this.value];

Solution 3:

You could pass an object literal as you came so close to doing:

return { name:this.name, value:this.value };

or you could pass an array:

return [this.name, this.value];

Of course if your code is executed in the global context, you'll be setting name and value on the window object. If you're using Evalcard as a constructor, you wont need a return statement, the object being created will automatically be set:

var e = newEvalcard(1);
console.log(e.name); //outputs "Ace" if you remove the return statement.

Solution 4:

Try:

return [this.name, this.value];

Solution 5:

Try this...

functionxyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]); 

Post a Comment for "How To Make Function Return More Than One Value"