gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:40:08 27 4
gpt4 key购买 nike

我想知道是否可以从原型(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;
};

最佳答案

您不能以这种方式使用多个 return 语句 - 只有第一个计算才会发生,但您可以返回一个对象数组,并从中获取您想要的内容。

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

关于javascript - 如何从对象函数javascript返回多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16916872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com