Javascript 如何使函数返回多个值

Javascript 如何使函数返回多个值,javascript,Javascript,这是我的代码: var Evalcard = function(number) { if (number == 1) { this.name = "Ace"; this.value = 11; } else if (number == 11) { this.name = "Jack"; this.value = 10; } else if (number == 12) { t

这是我的代码:

var Evalcard =  function(number) {
    if (number == 1) {
        this.name = "Ace";
        this.value = 11;
    }
    else if (number == 11) {
        this.name = "Jack";
        this.value = 10;
    }
    else if (number == 12) {
        this.name = "Queen";
        this.value = 10;
    }
    else if (number == 13) {
        this.name = "King";
        this.value = 10;
    }

    return {this.name,this.value};
我很确定这个
return
语句是不正确的。如何使函数返回多个值?任何帮助都会很好。

工作示例:

这个怎么样:

return [this.name, this.value];
尝试:


您需要更改它以返回数组或为要返回的对象提供键

所以


您可以传递一个对象文字,因为您非常接近这样做:

return { name:this.name, value:this.value };
或者您可以传递一个数组:

return [this.name, this.value];
当然,如果您的代码是在全局上下文中执行的,您将在
窗口
对象上设置
名称
。如果将
Evalcard
用作构造函数,则不需要返回语句,将自动设置正在创建的对象:

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

我将返回一个对象:

return {key1:value1, key2:value2}
然后您可以这样引用它:

myReturn.key1;

您可以通过多种不同的方式返回它:

排列

反对

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

return this.name+":"+this.value;

在这种情况下,您可能希望返回数组或对象文字:

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


return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];
试试这个

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

它是否依赖于对返回值的处理?我同意您可以简单地将结果作为对象返回,但这并不意味着这是唯一的方法。我认为在不了解全部背景的情况下,它可以走任何一条路。是的,这不是唯一的路。我现在同意你上次的编辑。@Oliver_Weiler——如果我以数组的形式返回它,我如何调用没有数组名称的值?@codeninja-
Evalcard(1)[0]
Evalcard(1)[1]
,其中括号中的值引用数组中值的对应键。@Gabriel_Ross——如果我以数组的形式返回它,如何调用没有数组名的值?(名称,值)=Evalcard(编号);下面所有这些答案都是好的,但不要在你的情况下使用
这个
。您需要声明两个变量:
var name,value取而代之。
return [this.name,this.value];
return {first:this.name, second:this.value};
return this.name+":"+this.value;
return { name: this.name, value: this.value };
// later: EvalCard(...).name; EvalCard(...).number;


return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];
function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);