JS:函数之间的返回值 - 范围

时间:2017-12-23 01:48:06

标签: javascript function scope

第一篇文章;做了一点挖掘但却无法找到我想要的东西(可能对该网站缺乏经验)。希望你们能帮忙:

- EDIT-- 经过讨论后的研究表明,我所寻找的是如何使用return将一个函数产生的值传递给另一个函数。

这与全球/本地范围有何关系?是从另一个本地或全局范围返回到函数的值吗?它是本地的原始功能,但全球可以访问?

  • 示例已更改*

var addition = function add(a, b) { var addTotal = (a+b);      return addTotal; }

 var multiply = function(c) {
 var multiplyTotal = c * 2 ; 
 return multiplyTotal; }

乘(除(2,3));

2 个答案:

答案 0 :(得分:1)

getUser返回userName,然后在调用lowerUserName时,将返回的值作为参数传递给它:

var getUser = function(userName) {
    var userName = prompt("Please enter your username?") || ''; //defend against null
    return userName;                                          // return userName
};

var lowerUserName = function(userName) {                      // expect user name as parameter (you can name this variable anything you want, it's only local to lowerUserName)
    var userNameLower = userName.toLowerCase();
                                                              // you should probably return userNameLower if you want to use it somewhere else
};

lowerUserName(getUser());                                     // call getUser and pass its return value directly to lowerUserName

lowerUserName(getUser());可以分为两个步骤,以便于理解:

var returnedValue = getUser();                                // the return value of getUser will be the value of userName
lowerUserName(returnValue);                                   // then we pass that value to lowerUserName when we call it

答案 1 :(得分:1)

我认为你可能过于复杂了,以下工作,因为prompt返回一个字符串(EDIT:或在第一条评论中指出的null,因此我轻易更新了一行以反映这一点);见https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

var userName = (prompt("Please enter your username?") || '').toLowerCase(); //FOOBAR
console.log(userName); //foobar