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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS:为什么这个值不是从一个函数传递到另一个函数?相关的知识,希望对你有一定的参考价值。

在前面的帖子中,我正在使用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());
答案

你必须返回那些变量。请尝试以下方法。

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个东西。所以我们需要将这两个变量都放到一个项目中。

以上是关于JS:为什么这个值不是从一个函数传递到另一个函数?的主要内容,如果未能解决你的问题,请参考以下文章

将值从一个函数传递到另一个JS

js函数相关

js函数相关

js函数相关

JS中函数参数值传递和引用传递

Python核心技术与实战——十三|Python中参数传递机制