对于之前的帖子,我正在使用return
,并将值从一个函数返回到另一个函数。我此刻有点卡住了。
下面,我尝试将userName
和validated
变量的结果作为参数传递给userCheck
函数。有些东西不对,请有人提供指导吗?谢谢。
var checkInput = function (userName) {
var validated = true; // For use later to decide whether userCheck runs.
var userName = prompt("What is your name?");
var checkType = typeof userName; // Save whether it's a string, number, null, or object.
if (checkType == "object") {
console.log("You clicked cancel.");
validated = false;
} //If cancel is clicked , do this.
else if (userName =="") {
console.log("You didn't enter a name");
validated = false;
} // If they just press enter, do this.
else if (isNaN(userName) == false) {
validated = false;
console.log("That's a number");
} //If it's a number, do this.
else {
return userName;
} //Otherwise, return userName for use elsewhere.
};
var userCheck = function(userEntry, validated) {
var userName = userEntry;
var validated = validated;
var correctMessage = (`Welcome back, ${userEntry}.`);
if (validated == true && userName == "alan" || userName == "rachel") { console.log(correctMessage); }
};
userCheck(checkInput());
答案 0 :(得分:0)
您必须返回这些变量。请尝试以下方法。
var checkInput = function(userName) {
var validated = true; // For use later to decide whether userCheck runs.
var userName = prompt("What is your name?");
var checkType = typeof userName; // Save whether it's a string, number, null, or object.
if (checkType == "object") {
console.log("You clicked cancel.");
validated = false;
} //If cancel is clicked , do this.
else if (userName == "") {
console.log("You didn't enter a name");
validated = false;
} // If they just press enter, do this.
else if (isNaN(userName) == false) {
validated = false;
console.log("That's a number");
} //If it's a number, do this.
return {
userName: userName,
validated: validated
};
};
var userCheck = function(object) {
var userName = object.userName;
var validated = object.validated;
var correctMessage = (`Welcome back, ${userName}.`);
if (validated == true && userName == "alan" || userName == "rachel") {
console.log(correctMessage);
}
};
userCheck(checkInput());
现在将返回包含userName
和validated
的对象。然后在userCheck
函数中查看该对象中的值。这是因为你只能在函数中返回1个东西。所以我们需要将这两个变量都放到一个项目中。