如何将多个变量从函数传递给函数 [英] How to pass multiple variables from function to function

查看:100
本文介绍了如何将多个变量从函数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


这个问题是相关的,但与
不同 javascript:在另一个函数中获取函数变量的值
&
如何在javascript中的函数之间传递变量

我一直想知道如何将变量从一个函数传递到另一个函数,可以找到答案以上。但更大的问题是如何传递多个变量,感觉上面找到的答案的语法会变得过于复杂,最终变得不可读。

I have been wondering for some time now how to pass a variable from one function to another, which answer can be found above. But the bigger question is how to pass multiple variable, sense the syntax of the answers found above can become overly complex, and it ends up being unreadable.

不要介意我在示例中添加和警告。 这是一个dummie示例,如下面的exaple所述。这个问题的目的在下面的段落中用粗体清楚地说明。

Don't mind the adding and alerting that I am doing in the example. This is a dummie example as stated below the exaple. The purpose of this question is clearly stated in the paragraph below in bold.

所以这是我的问题,你如何通过从一个函数到另一个函数的多个变量,例如:

So here is my question, How do you pass multiple variable from one function to another, example:

function definingVars() {
  var one = 1;
  var two = 2;
  var three = 3;
  var four = 4;
  var five = 5;
  var six = 6;
  var seven =  7;
  var eight = 8;
  var nine = 9;
  var ten = 10;
}

function addingUp() {
  definingVars();
  alert("Alerting var total");
  var total = one + two + three + four + five + six + seven + eight + nine;
  alert(total);
  alert("Alerting var ten");
  alert(ten);
}

我知道它不是正确的方法来解决这个问题但我想在这里做一个dummie示例。

I know that it is not the correct way to approach this. But I'm trying to make a dummie example here.

推荐答案

返回一个属性包含所需值的对象:

Return an object whose properties contain the desired values:

function definingVars() {
  return {
    one: 1,   two: 2,     three: 3,   four: 4,   five: 5,
    six: 6,   seven: 7,   eight: 8,   nine: 9,   ten: 10
  };
}
function addingUp() {
  var data = definingVars();
  return data.one + data.two + data.three + data.four + data.five
         + data.six + data.seven + data.eight + data.nine;
}

如果你想避免重复数据,你可以使用,但请注意它是慢的,不好的做法,并且在严格模式下不允许:

If you want to avoid repeating data, you can use with, but note it's slow, bad practice and not allowed in strict mode:

function addingUp() {
  with(definingVars()) {
    return one + two + three + four + five + six + seven + eight + nine;
  }
}

这篇关于如何将多个变量从函数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆