search

Home  >  Q&A  >  body text

javascript - How does the callback function access the value under the current function?

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

大家讲道理大家讲道理2789 days ago581

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-16 13:37:48

    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);
    }
    

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:37:48

    Put bookARR[i] in callback

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 13:37:48

    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

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 13:37:48

    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

    reply
    0
  • Cancelreply