angular - 错误类型错误:无法读取未定义角度 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;
}
}
解决方案
长度和索引不是一回事。索引从 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
推荐阅读
- angular - 仅在移动视图上隐藏 ngx-popover
- c++ - 使用指针变量打印特定的数组变量
- android - 将 FloatArray 音频缓冲区保存到 Android 上的 wav 文件
- excel - 我如何将此代码转换为更短的代码?可能通过数组?
- javascript - 在 shell exec 期间无法使用 socket.io 发出当前服务器状态
- javascript - 如何从 ids 对象中删除项目
- python - 从 Postgresql 查询大数据集并进行处理
- javascript - JS 开发人员是否应该阅读 ECMAScript 规范?
- javascript - 更改嵌套对象的引用是否正在更改对根对象的引用?
- matplotlib-basemap - 如何使用 python 在伦敦地图上添加散点图