简体   繁体   中英

Array Says Its Length Is 0 But Console Says Otherwise

Good Afternoon, I have encountered a problem with my code: I have a for function adding values to an array variable but whenever I run the page it gives me an error stating that the array is empty. Here's the code adding values to the array:

    if(this.Type === "Image") {
        this.Frames = [];
        for(var i = 0; i <= Sources.length - 1; i++) {
            var Img = new Image();
            Img.src = Sources[i];
            this.Frames["Frame" = i] = Img;
        }
    } else {
        this.Frames = [];
        for(var i = 0; i <= Sources.length - 1; i++) {
            this.Frames["Frame" + i] = Sources[i];
        }
    }

The code runs fine. How do I know that? Well I went on the JavaScript console and checked what value the array had. It said Frames[0], but when I collapsed it, it had Frame0, and when I collapsed that, the source it had was the correct source. So, what is going on with this? Is it a glitch or am I doing something wrong that I didn't know of before? Thanks in advance.

这就是控制台上显示的内容

That's because JavaScript only has numeric arrays. It does not have associative arrays.

When you do: this.Frames["Frame" + i] = Sources[i]; , what you are doing is adding a property to the array (in JavaScript, everything is an object, and can therefore have properties). You are not actually pushing to the array.

One thing you can do is use an object instead: this.Frames = {}; .

Or, you can .push() onto the array and use it as a numeric array.

this.Frames[i] = Sources[i];
// or
this.Frames.push(Sources[i]);

The .length property of JavaScript arrays only counts properties whose names are strings that look like integers (like "0", "1", etc). You can add whatever properties you want to an array instance, but only numeric properties affect the length of the array.

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