JS:为什么这个值从一个函数传递到另一个函数?

时间:2017-12-23 06:07:54

标签: javascript function return arguments

对于之前的帖子,我正在使用return,并将值从一个函数返回到另一个函数。我此刻有点卡住了。

下面,我尝试将userNamevalidated变量的结果作为参数传递给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());

1 个答案:

答案 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());

现在将返回包含userNamevalidated的对象。然后在userCheck函数中查看该对象中的值。这是因为你只能在函数中返回1个东西。所以我们需要将这两个变量都放到一个项目中。