How to understand such a problem? (don't test, leave your analysis process and results)

as detailed in the title: just after the interview, I came to write down such a question. has not been tested yet, and I hope you will not test it, leaving your analysis process and answers

.

1. Everything is caused by a line I wrote that uses the reduce method to sum the array:

var arr = [1,2,3];
arr.reduce((sum,value) => {
    return sum + value
},0)
< hr >

2, but when the interviewer added something to it, he was a little confused:

var arr = [1,2,3];
arr.reduce((sum,value) => {
    setTimeout(() => console.log(1), 0)
    return sum + value
},0)

I said, first output the sum result, and then output 1 (personal understanding does not know right or wrong, he did not say much. )

< hr >

3. Then he revised it again and thought about it or kept my answer

.
var arr = [1,2,3];
arr.reduce((sum,value) => {
    setTimeout(() => console.log(1), 1000)
    return sum + value
},0)

how do you analyze and understand it?

Mar.25,2021

the first one is 6, so there's nothing to say.
the second is the first 6, immediately followed by 3 1s.
the third is the first 6, one second followed by three 1s.
the interviewer wants to test the eventloop, of js, which is simply the priority of the event. I can't remember exactly which noun. SetTimeout doesn't have the same priority as code that executes sequentially. Take the second, for example, the first time reduce encountered settimeout, he put settimeout in the queue of secondary priority, and then the second time, the third time. When the reduce is finished, the task of the secondary priority queue begins to be executed. The third one is even clearer: wait a second before executing the secondary priority queue.


personal understanding:

arr.reduce passes the second parameter, so it executes arr.length times, that is, arr.length times setTimeout,. The question is as follows:

  

this is an examination of time loops. Your code will be executed on the execution stack and the setTimeout will be placed in the task queue. When executing, you should first run the code in the execution stack, and then put the code in the task queue into the execution stack for execution. So setTimeout will output later.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e51ef6-45182.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e51ef6-45182.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?