javascript - How does the callback function access the value under the current function?
大家讲道理
大家讲道理 2017-05-16 13:35:48
0
4
550

I defined an array variable in the function, which contains 6 elements, and then called the callback function in the function. The value of the array variable cannot be accessed in the callback function, but the length attribute can be accessed. I feel very confused and don't know how to solve it.

for(var i=0;i<bookARR.length;i++){//在该书中写入 有借图书馆id
                //因为图书馆表需要所有书籍的_id,所以检测有时,记录id
                console.log("在外面"+bookARR[i]);//9787539989891 9787533946777 9787569914078 9787513316286 9787218113180 9787535491978
                 Book.getBookByISBN(bookARR[i],function(err,book){
                    if(!book||err){
                        console.log("huidiao"+bookARR.length);//6
                        console.log("在里面"+bookARR[i]);//undefined undefined undefined undefined undefined undefined
                        newBook.push(bookARR[i]);
                    }else{
                        newBook_id.push(book._id);
                    }
                    ep.emit('examine');
                })
            }

Book.getBookByISBN() is a function I defined in other modules

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
伊谢尔伦

Because

for (var i = 0; i<10; i++) {
   setTimeout(function(){console.log(i)});
}

for (var i = 0; i<10; i++) {
    (function(i){
       setTimeout(function(){console.log(i)});
    })(i)
}

So

for(var i=0;i<bookARR.length;i++){
    (function(i) {
        Book.getBookByISBN(bookARR[i],function(err,book){
            if(!book||err){
                console.log("huidiao"+bookARR.length)
                console.log("在里面"+bookARR[i]);
                newBook.push(bookARR[i]);
            }else{
                newBook_id.push(book._id);
            }
            ep.emit('examine');
        })
    })(i);
}
巴扎黑

Put bookARR[i] in callback

左手右手慢动作

The reason has been mentioned before. In fact, it is just to pass in bookArr[i] where you define the callback call in the Book.getBookByISBN() function. Understand the formal parameters and actual parameters

漂亮男人

This is a typical asynchronous problem, and the scope of i is still within it.
Because I’m waiting for you asynchronously getBookByISBN 方法调用callback的时候 i=bookARR.length。这已经越界了,所以是undefined.

Solution:
1. Closure
2.let

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template