简体   繁体   中英

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. it prints the array as well as gives 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] .

You have i < deceding.length , so i will range between 0 and 2 (Less than length, which is 3).

Next you do 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. ie, you try to get deceding[3] which is undefined.

在此处输入图片说明

Can you change an execute environment? I've never seen undefined in my node.

I guest that you run this function on chrome console . Actually your function is return nothing. So it is console undefined . Is this the same what you got ? http://prntscr.com/hgma9g

在此处输入图片说明

The chrome console alway print out what returned from last line of code. So if this is an assignment or function call without return a value it will print 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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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