这是什么意思 []?

时间:2019-05-30 16:13:23

标签: angular typescript

我不明白在以下代码中在[0]前面使用dish.id and dish.featured的原因:

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable()
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: number): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}

这是Dish类:

import { Comment } from './comment';

export class Dish {
    id: number;
    name: string;
    image: string;
    category: string;
    label: string;
    price: string;
    featured: boolean;
    description: string;
    comments: Comment[];
}

2 个答案:

答案 0 :(得分:3)

阅读此.filter()dish.id and dish.featured之所以最后有[0]的原因是因为filter总是以数组形式返回结果。

var words = ['a','spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length == 1);

console.log(result);

答案 1 :(得分:2)

过滤器返回一个数组,因此当您使用[0]时,意味着选择第一个选择。 您可以在此处了解更多信息:Filter