gpt4 book ai didi

angular - typescript 数组按索引查找元素

转载 作者:太空狗 更新时间:2023-10-29 17:04:16 28 4
gpt4 key购买 nike

查找并分配具有 categoryId 的 CategoryApi 对象

export class CategoryApi {
categoryId: number;
name: string;
}

categories: CategoryApi[];
selectedCategory: CategoryApi;

selectedCategory = categories.findByIndex(2); //looking for categoryApi by categoryId = 2

我找到了这个 javascript 选项,但 Typescript 提示这个函数

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

最佳答案

JS中没有findByIndex方法,只有findIndex方法。

您可以使用filterfind 方法按索引获取项目:

//ES2015

selectedCategory = categories.find(item => item.categoryId === 1);

//ES5

selectedCategory = categories.filter(item => item.categoryId === 1)[0];

关于angular - typescript 数组按索引查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41008452/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com