简体   繁体   中英

Array length issue with proper use of push

I'm aware of the title sounds very familiar to a often asked question about associative arrays and the problem of their length. However I didn't find a solution for my problem over here on Stack Overflow yet.

The problem is, .length is always outputting 0 instead of the wanted amount, which in this testing case would be 12. When I output it via console.log I get 12 entries and I can see the length attribute with the correct value. I attached my firebug output:

images: Array[12] 
    0: "img1.jpg"
    1: "img2.jpg"
    2: "img3.jpg"
    3: "img4.jpg"
    4: "img5.jpg"
    5: "img6.jpg"
    6: "img7.jpg"
    7: "img8.jpg"
    8: "img9.jpg"
    9: "img10.jpg"
    10: "img11.jpg"
    11: "img12.jpg"
    length: 12
    __proto__: Array[0]

The following code snippet fills the array:

this.images.push(el.toDataURL());

when i now call console.log(this,this.images,(this.images).length); its always 0 instead of 12.

Any help would be appreciated.

The script on fiddle. (output on console)

http://jsfiddle.net/EL2xR/

When you say this.img.onload you make it asynchronous, your init is run but then immediately after the method getImages, which finds the aImages empty at that moment in time. You should consider checking if all images are loaded before running getImages to get the correct result.

Here is a modified example that works. You can tweak it more if needed! http://jsfiddle.net/EL2xR/1/

 interval = setTimeout(function() {
                _this.getImages(from, to);
            }, 1000);

Check for where this.loaded appears in the code, that one flag I used to know that everything is loaded! And then with setTimeout just run the same method until loaded is true!

ah - i see what you mean.

So the problem is just that you are printing it to the console when it is empty, but the array contents are updated after you log it.

add this after your initial console.log to see :

  var that = this;
  setTimeout(function() {
       console.log("Later...");
       console.log(that,that.aImages,that.aImages.length);
  });

Perhaps confusing you is that "this" and it's properties are live in the console, so expanding the sprite - you see that it's aImages is full, but they were empty when you first printed them.

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