简体   繁体   English

如何正确获取数组长度

[英]How to correctly get length of array

I'm having a bit of a problem so i have an array with objects when i log it it displays everything fine but when i try the .length function it returns 0 for some reason.我遇到了一些问题,所以当我记录它时,我有一个包含对象的数组,它显示一切正常,但是当我尝试.length函数时,由于某种原因它返回0

Here's my code:这是我的代码:

async getTicketType(updatedTicketType) {
    await this.getTicketTypes();
    if (this.typeOptions) {
        console.log('ik kom hier');
        console.log(this.typeOptions);
        console.log(this.typeOptions.length);
        for (let i = 0; i < this.typeOptions.length; i++) {
            console.log('ik kom hier');
            if (this.typeOptions[i]["value"] === updatedTicketType) {
                this.currentTypeOptions = this.typeOptions[i];
            }
        }
    }
}

And here's a picture of the logs:这是日志的图片:

这是日志的图片

This is because your array has 10 undefined values therefore it does not actually have a length property, if you make sure that there is some value in each element then you will be able to get the array.这是因为您的数组有 10 个未定义的值,因此它实际上没有长度属性,如果您确保每个元素中都有一些值,那么您将能够获得该数组。 It's a feature of JS and how the length property on the array is computed.这是 JS 的一个特性以及如何计算数组的长度属性。

You can try to parse it to an array again:您可以尝试再次将其解析为数组:

// arr is an array with contains 10 items
var arr = JSON.parse(JSON.stringify(this.typeOptions));

Then, continuing with the loop...然后,继续循环......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM