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