如何从对象函数javascript返回多个值?

时间:2013-06-04 11:40:35

标签: javascript function prototype

我想知道是否可以从原型对象返回多个值。我需要返回几个数组的值,并在稍后调用它们。下面是我的代码示例..如果需要,我可以展示一个JSFiddle。谢谢!!

 EmployeeObj.prototype.showEmployee = function(emPhoto0,emPhoto01){
     var employeePhoto = new Array();
     employeePhoto[emPhoto0] = new Image();
     employeePhoto[emPhoto0].src = "pics/taylor.jpg";
     employeePhoto[emPhoto01] = new Image();
     employeePhoto[emPhoto01].src = "pics/roger.jpg";

     var showPhoto1 = employeePhoto[emPhoto0];
     var showPhoto2 = employeePhoto[emPhoto1];

     return showPhoto1;
     return showPhoto2;
 };

4 个答案:

答案 0 :(得分:1)

您不能以这种方式使用多个return语句 - 只会发生第一次评估,但您可以返回 Object Array ,并从中获取您想要的内容。

EmployeeObj.prototype.showEmployee = function (emPhoto0, emPhoto01) {
    var employeePhoto = new Array();
    employeePhoto[emPhoto0] = new Image();
    employeePhoto[emPhoto0].src = "pics/taylor.jpg";
    employeePhoto[emPhoto01] = new Image();
    employeePhoto[emPhoto01].src = "pics/roger.jpg";
    var showPhoto1 = employeePhoto[emPhoto0];
    var showPhoto2 = employeePhoto[emPhoto1];
    return {'showPhoto1': showPhoto1, 'showPhoto2': showPhoto2};
    // or [showPhoto1, showPhoto2];
};

然后您可以通过

访问
var em = new EmployeeObj(/* ... */),
    photos = em.showEmployee(/* ... */);
photos['showPhoto1']; // or photos['showPhoto2']
// or photos[0], photos[1], if you used the Array version

答案 1 :(得分:1)

您可以将2个结果合并到一个对象中:

return { photo1: showPhoto1, photo2: showPhoto2 };

答案 2 :(得分:0)

不,您不能在一个函数中执行多个return语句。但是您可以返回包含结果的数组。在你的情况下这很简单:

return employeePhoto;

答案 3 :(得分:0)

这个问题的现代答案是通过返回数组来使用destructuring,并将数组解构为调用方的变量:

EmployeeObj.prototype.showEmployee = function (emPhoto0, emPhoto01) {
    ...
    return [showPhoto1,showPhoto2]
}

// Calling showEmployee
[showPh1, showPh2] = <Employee>.showEmployee(emPh0, emPh01)

现在,在浏览器和node.js应该很快就会出现对这种模式的支持。

关于这种模式最酷的是它允许我们通过返回值和错误来实现与Go lang Error handling匹配的替代错误处理模式。