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

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

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
    巴扎黑

    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 asynchronouslygetBookByISBN方法调用callback的时候i=bookARR.length。这已经越界了,所以是undefined.

        Solution:
        1. Closure
        2.let

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!