简体   繁体   English

Console.log和函数返回(JavaScript)

[英]Console.log and function return (Javascript)

Apologies if this has been asked before, I am a relative newcomer to coding and not so sure about the keywords to search for. 不好意思,如果以前有人问过这个问题,我是编码的新手,对要搜索的关键字不太确定。

This function assigns some random values for later timeout: 此函数为以后的超时分配一些随机值:

function getDelays(tonesTotal){
    var return_array = new Array();
    for (var i = 0; i < tonesTotal; i++)
    {
        var r = getRandInt(0, 600);    
        var delay = r * 1000;
        return_array.push(delay);  
    }
    console.log(return_array);
    return return_array; 
}

In this manner, the console properly logs return_array ... but flip the order: 通过这种方式,控制台可以正确地记录return_array ...,但可以return_array顺序:

    return return_array; 
    console.log(return_array);

... and the console is silent. ...并且控制台是静默的。 Why? 为什么?

The return statement exits the current function. return语句退出当前函数。

No further code will run. 不会再运行任何代码。

The return statement ends function execution and specifies a value to be returned to the function caller. return语句结束函数执行并指定要返回给函数调用者的值。

Which in effect means, anything after the return statement will not be reached, and thus not executed. 实际上,这意味着在return语句之后的所有内容都不会到达,因此不会执行。 There are IDE editors that will warn you about this problem. 有IDE编辑器会警告您有关此问题的信息。

The return statement exits the function and the next code statements are not run. return语句退出该函数,并且下一个代码语句不运行。 If you use a linter tool like ESLint, JSLint they will show a warning that unreachable code is detected . 如果您使用诸如ESLint,JSLint之类的linter工具,它们将显示警告,指出检测到无法访问的代码

The return statement ends function execution and specifies a value to be returned to the function caller. return语句结束函数执行并指定要返回给函数调用者的值。 If you don't specify a value in the return statement and use it like return the function returns undefined . 如果您未在return语句中指定值,而是像return一样使用它,则该函数将返回undefined

The return statement exits program execution out of a function and back to where the function was called. return语句使程序退出函数的执行,返回到调用该函数的位置。 The reason why console.log() is not called is because if the return statement executes, all code underneath that function is never reached. 未调用console.log()的原因是,如果执行return语句,则永远不会到达该函数下的所有代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM