简体   繁体   English

错误类型错误:无法读取未定义 angular 8 的属性“长度”

[英]ERROR TypeError: Cannot read property 'length' of undefined angular 8

I made a site to pick a cat at random like Cat and Mash, but I have an error that I cannot understand.我做了一个网站来随机挑选一只猫,比如 Cat and Mash,但我有一个我无法理解的错误。

I have a JSON object in which there are urls that contain images.我有一个 JSON object ,其中有包含图像的网址。 I need to display the images randomly but not 2 times the same image.我需要随机显示图像,但不是同一图像的 2 倍。

Console:安慰:

在此处输入图像描述

Why is length undefined?为什么length未定义?

import { Component, OnInit } from '@angular/core';
import { CatService } from '../services/cat.service';
import { CatList, Cat } from '../model/cat';

@Component({
  selector: 'app-cat',
  templateUrl: './cat.component.html',
  styleUrls: ['./cat.component.css']
})
export class CatComponent implements OnInit {
    twoCatsArray: Cat[] = [];
    allcats: Cat[];
    constructor(private catService: CatService) {}
    ngOnInit() {
        this.showMeTwoCats();
    }
    showMeTwoCats() {
        this.catService.getCats().subscribe((cats: CatList) = > {
            this.allcats = cats.images;
            this.twoCatsArray = this.chooseTwoRandomCats(this.allcats);
        });
    }
    chooseTwoRandomCats(cats: Cat[]): Cat[] {
        const firstCatIndex = this.getRandomIndex(cats.length);
        const secondCatIndex = this.getRandomIndex(cats.length, firstCatIndex);
        return [cats[firstCatIndex], cats[secondCatIndex]];
    }
    getRandomIndex(maxValue: number, differentThanValue ? : number): number {
        let index: number;
        do {
            index = this.getRandomInt(maxValue);
        } while (index === differentThanValue);
        return index;
    }
    getRandomInt(max): number {
        return Math.floor(Math.random() * Math.floor(max));
    }
    voteForThisCat(id: string) {
        const likedCatindex = this.allcats.findIndex((cat: Cat) = > cat.id === id);
        const newRating = this.getIncrementedCatRatingValue(this.catService.catVote[likedCatindex].rating);
        this.catService.catVote[likedCatindex].rating = newRating;
        this.twoCatsArray = this.chooseTwoRandomCats(this.allcats);
    }
    getIncrementedCatRatingValue(rating: number | undefined): number {
        return rating ? ++rating : 1;
    }
}

Length and index aren't the same thing.长度和索引不是一回事。 Indices are 0 based, length starts at 1. So, An array with 2 items will have a length of 2, but the index of the second item is index 1. You need to subtract 1 from the length.索引从 0 开始,长度从 1 开始。因此,包含 2 项的数组的长度为 2,但第二项的索引是索引 1。您需要从长度中减去 1。 Its selecting an index that doesnt exist.它选择了一个不存在的索引。

 var cats = []; cats.push('Felix'); cats.push('Molly'); console.log('L: ' + cats.length); // L: 2 console.log('0: ' + cats[0]); // 0: Felix console.log('1: ' + cats[1]); // 1: Molly console.log('I: ' + cats[cats.length]); // I: Undefined

DO you have any values for this.allCats ?你对this.allCats有什么价值观吗?

If Yes如果是

You are getting the error because you are trying to get element from a position that doesn't exist in array.您收到错误是因为您试图从数组中不存在的 position 获取元素。

index in array is a read-only property that is the zero-based index of the match in the string.数组中的索引是一个只读属性,它是字符串中匹配项的从零开始的索引。

Each element in the array has an index , which is just its numerical position in the sequence of elements.数组中的每个元素都有一个索引,即元素序列中的数字 position。 If the array is A, then the i-th element of the array is A[i].如果数组是 A,那么数组的第 i 个元素是 A[i]。 The number of elements in an array is called its length.数组中元素的数量称为它的长度。 The length of an array A is A.length.数组 A 的长度是 A.length。

So if you wish to grab the nth element from array A, you need to access A[n-1]所以如果你想从数组 A 中获取第 n 个元素,你需要访问A[n-1]

I feel I'm missing some info, but with what I've got, you have the problem in chooseTwoRandomCats, to which you are passing this.allCats, which is undefined.我觉得我遗漏了一些信息,但是根据我所掌握的情况,您在 chooseTwoRandomCats 中遇到了问题,您将 this.allCats 传递给该问题,这是未定义的。

You do this:你来做这件事:

allcats: Cat[];

then you do this:然后你这样做:

this.catService.getCats().subscribe((cats: CatList) => {
  this.allcats = cats.images;
  this.twoCatsArray = this.chooseTwoRandomCats(this.allcats);
});

to end up doing this:最终这样做:

const firstCatIndex = this.getRandomIndex(cats.length);
const secondCatIndex = this.getRandomIndex(cats.length, firstCatIndex);

so, is catService.getCats() returning any cats?那么, catService.getCats() 是否返回任何猫?

Your CatList model has an "images" property?您的 CatList model 有“图像”属性吗? It seems to be an array, so it probably don't have.它似乎是一个数组,所以它可能没有。

If this is the case, you're assigning undefined to "allcats".如果是这种情况,您将 undefined 分配给“allcats”。 If not, check the result property images of cats, maybe your service doesn't return anything.如果没有,请检查猫的结果属性图像,也许您的服务没有返回任何内容。

To avoid the error (but not resolve) you can do something like this:为避免错误(但无法解决) ,您可以执行以下操作:

this.allcats = cats.images || [];

[ [json

I copied a json I forgot the key images in my json我复制了 json 我忘记了 json 中的关键图像

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

相关问题 错误TypeError:无法读取Angular 7 Drag and Drop中未定义的属性“length” - ERROR TypeError: Cannot read property 'length' of undefined in Angular 7 Drag and Drop TypeError无法读取未定义的属性“ length”-角度4 - TypeError cannot read property “length” of undefined - angular 4 Angular 8“类型错误:无法读取未定义的属性‘长度’” - Angular 8 "TypeError: Cannot read property 'length' of undefined" 类型错误:无法读取角度 6 中未定义的属性“长度” - TypeError: Cannot read property 'length' of undefined in angular 6 TypeError:无法读取角度4中未定义的属性“ length” - TypeError: Cannot read property 'length' of undefined in angular 4 错误类型错误:无法读取未定义的属性“长度” - ERROR TypeError: Cannot read property 'length' of undefined Angular4:ERROR TypeError:访问length属性时无法读取未定义的属性“length” - Angular4: ERROR TypeError: Cannot read property 'length' of undefined while accessing length property Angular 4-无法读取未定义的属性“ length”中的错误 - Angular 4 - ERROR in Cannot read property 'length' of undefined 错误TypeError:无法读取undefined |的属性“0” Angular 4 - ERROR TypeError: Cannot read property '0' of undefined | Angular 4 Angular:ERROR TypeError:无法读取undefined的属性___ - Angular: ERROR TypeError: Cannot read property ___ of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM