从函数返回多个值返回调用

时间:2023-02-03 02:02:32

I'm a noobie... and I'm sure there is better terminology for what I'm trying to ask (callback?) but basically I want to learn how to get values calcluated in a function back to where the function was called from. E.g.:

我是一个noobie ...而且我确信有更好的术语可以解释我的问题(回调?)但基本上我想学习如何将函数中的值计算回到调用函数的位置从。例如。:

$(function() {
    setValues();
    console.log(val1, val2, val3);

});

function setValues() {
    var val1 = 10;
    var val2 = 20;
    var val3 = 30;  
}

1 个解决方案

#1


2  

Try something like this:

尝试这样的事情:

$(function() {
    var myvalues = setValues(); //this stores the values you got from the function

   //now you can do something like console.log(myvalues.value1) to get the first value


});

function setValues() {
    var val1 = 10;
    var val2 = 20;
    var val3 = 30;  
    return {value1: val1, value2: val2, value3: val3} //this sends the data back to the original place where you called the function
}

I would suggest reading this article on object literals.

我建议阅读关于对象文字的这篇文章。

#1


2  

Try something like this:

尝试这样的事情:

$(function() {
    var myvalues = setValues(); //this stores the values you got from the function

   //now you can do something like console.log(myvalues.value1) to get the first value


});

function setValues() {
    var val1 = 10;
    var val2 = 20;
    var val3 = 30;  
    return {value1: val1, value2: val2, value3: val3} //this sends the data back to the original place where you called the function
}

I would suggest reading this article on object literals.

我建议阅读关于对象文字的这篇文章。