简体   繁体   English

findindex 返回 -1 即使数组不为空

[英]findindex return -1 Even though the array is not empty

I use the getMovie() function to get the data in the array through the id and at the "theatres" the data is returned to me correctly, but at the "trending or popular" it does not return any data and the index value is -1, although the array is not empty我使用 getMovie() function 通过 id 获取数组中的数据,并在“剧院”将数据正确返回给我,但在“趋势或流行”时,它不返回任何数据,索引值为-1,虽然数组不为空

export class MovieComponent implements OnInit {
  type = '';
  id = '';
  url = '';
  movies: any;
  movie: any;


  constructor(private route: ActivatedRoute, private http: HttpClient) {}

  ngOnInit(): void {
    this.type = this.route.snapshot.params['type'];
    this.id = this.route.snapshot.params['id'];
    if (this.type === 'Trending') {
      this.url = 'http://localhost:4200/assets/data/trending-movies.json';
    }
  else  if (this.type === 'Theatres') {
      this.url = 'http://localhost:4200/assets/data/theatre-movies.json';
    }
   else if (this.type === 'Popular') {
      this.url = 'http://localhost:4200/assets/data/popular-movies.json';
    }
    this.getMovie();
  }

  getMovie() {
    this.http.get(this.url).subscribe((movies) => {
      this.movies = movies;
      let index = this.movies.findIndex(
        (movie: { id: string }) => movie.id == this.id
      );
      console.log(index);
      if (index > -1) {
        this.movie = this.movies[index];
      }
    });
  }
}

Here's the documentation on MDN .这是MDN 上的文档

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. findIndex()方法返回满足提供的测试 function 的数组中第一个元素的索引。 If no elements satisfy the testing function, -1 is returned.如果没有元素满足测试 function,则返回 -1。

Also, when working with typescript, you might want to actually type your members, instead of typing everything as any.此外,在使用 typescript 时,您可能希望实际键入您的成员,而不是键入任何内容。

It returns -1 because there aren't any elements that satisfy the testing function它返回 -1 因为没有任何元素满足测试 function

Try checking your searching terms, because as others have noted, -1 doesn't mean the array is not empty but rather no results came up with your searching term.尝试检查您的搜索词,因为正如其他人所指出的那样,-1 并不意味着数组不为空,而是您的搜索词没有结果。

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

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