![](/img/trans.png)
[英]JavaScript cache return value of a function with more than one parameter
[英]how to make function return more than one value
这是我的代码:
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
语句是不正确的。 如何让 function 返回多个值? 任何帮助都会很棒。
在这种情况下,您可能希望返回一个数组或 object 文字:
return { name: this.name, value: this.value };
// later: EvalCard(...).name; EvalCard(...).number;
return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];
这个怎么样:
return [this.name, this.value];
您可以通过 object 文字,因为您非常接近这样做:
return { name:this.name, value:this.value };
或者你可以传递一个数组:
return [this.name, this.value];
当然,如果您的代码在全局上下文中执行,您将在window
object 上设置name
和value
。 如果您使用Evalcard
作为构造函数,则不需要return 语句,正在创建的 object 将自动设置:
var e = new Evalcard(1);
console.log(e.name); //outputs "Ace" if you remove the return statement.
工作示例: http://jsfiddle.net/CxTWt/
var Evalcard = function(number) {
var evalName, evalValue;
if (number == 1) {
evalName= "Ace";
evalValue = 11;
}else if (number == 11) {
evalName = "Jack";
evalValue = 10;
}else if (number == 12) {
evalName= "Queen";
evalValue= 10;
}else if (number == 13) {
evalName= "King";
evalValue = 10;
}
return {name: evalName, value: evalValue};
}
alert(Evalcard(1).name+" "+Evalcard(1).value);
尝试:
return [this.name, this.value];
尝试这个...
function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);
您需要更改它以返回一个数组或为您返回的 object 提供密钥
所以
return [this.name,this.value];
或者
return {name:this.name,value:this.value};
我会返回一个 object:
return {key1:value1, key2:value2}
然后你可以像这样引用它:
myReturn.key1;
您可以通过多种不同方式返回它:
大批
return [this.name,this.value];
Object
return {first:this.name, second:this.value};
细绳
return this.name+":"+this.value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.