简体   繁体   English

传递数组不起作用使我在控制台中未定义

[英]Passing an array infunction gives me undefined in console

In below javascript code, if I only prints nums which is array pass to the function. 在下面的javascript代码中,如果我仅打印将数组传递给函数的数字。 it prints the array as well as gives undefined. 它打印数组并给出undefined。 So below logic gives an answer but in next line it prints out undefined. 因此,下面的逻辑给出了答案,但是在下一行中,它未打印出来。

function getSecondLargest(nums) {

       let deceding = nums.sort(function(a, b){return b-a});


    for(let i = 0; i<deceding.length ; i++)
        {
            if(deceding[i]>deceding[i+1])
                {
                    console.log(deceding[i+1]);
                    break;
                }
        }


}

Pretend deceding is [0, 1, 2] . 假装为[0, 1, 2]

You have i < deceding.length , so i will range between 0 and 2 (Less than length, which is 3). 您有i < deceding.length ,所以i范围是0到2(小于length,即3)。

Next you do console.log(deceding[i + 1]); 接下来,执行console.log(deceding[i + 1]); , but for the later iterations of the loop i + 1 will be greater than 2 which is the last index of the array, meaning it is undefined. ,但对于循环的后续迭代,i + 1将大于2,这是数组的最后一个索引,这意味着它是未定义的。 ie, you try to get deceding[3] which is undefined. 即,您尝试获取未定义的deceding[3]

在此处输入图片说明

Can you change an execute environment? 您可以更改执行环境吗? I've never seen undefined in my node. 我从未在节点中看到undefined

I guest that you run this function on chrome console . 我请您在chrome console上运行此功能。 Actually your function is return nothing. 实际上,您的函数什么也不返回。 So it is console undefined . 因此它是控制台undefined Is this the same what you got ? 这和你得到的一样吗? http://prntscr.com/hgma9g http://prntscr.com/hgma9g

在此处输入图片说明

The chrome console alway print out what returned from last line of code. chrome控制台始终打印出从最后一行代码返回的内容。 So if this is an assignment or function call without return a value it will print undefined . 因此,如果这是一个赋值或函数调用而没有返回值,则它将打印undefined So don't worry, your function worked as expected. 所以不用担心,您的功能按预期工作。

There is a way to by pass this by assign and return the value you want to log in the function. 有一种方法可以通过赋值并返回您要在函数中登录的值来进行传递。 :) :)

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

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