首页 > 解决方案 > 错误类型错误:无法读取未定义角度 8 的属性“长度”

问题描述

我做了一个网站来随机挑选一只猫,比如 Cat and Mash,但我有一个我无法理解的错误。

我有一个 JSON 对象,其中有包含图像的 url。我需要随机显示图像,但不是同一图像的 2 倍。

安慰:

在此处输入图像描述

为什么是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;
    }
}

标签: angulartypescript

解决方案


长度和索引不是一回事。索引从 0 开始,长度从 1 开始。因此,包含 2 项的数组的长度为 2,但第二项的索引是索引 1。您需要从长度中减去 1。它选择了一个不存在的索引。

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


推荐阅读