打字稿数组按索引查找元素
Typescript Array find element by index
查找并分配具有 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 }
您可以使用查找方法:
selectedCategory = categories.find(c => c.categoryApi == 2);
问题是 find
函数没有在类型文件中列出。
首先,忽略错误消息并尝试!
其次,您可以编辑打字文件:
- 将
find
更改为 filter
并按 F12(转到声明)
- 将此行复制到类型文件中并将函数重命名为
find
并将返回值改为单个对象而不是数组!
- 保存该文件
- 在您的代码中将您的背部
filter
重命名为 find
..
JS中没有findByIndex方法,只有findIndex.
方法
您可以使用 filter 或 find 方法按索引获取项目:
// ES2015
selectedCategory = categories.find(item => item.categoryId === 1);
// ES5
selectedCategory = categories.filter(item => item.categoryId === 1)[0];
获取具体的参数值。
使用此代码
this.categories.find(item => item.categoryId === 1).categoryId
Where categoryId 可以是你想要的任何字段
查找并分配具有 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 }
您可以使用查找方法:
selectedCategory = categories.find(c => c.categoryApi == 2);
问题是 find
函数没有在类型文件中列出。
首先,忽略错误消息并尝试!
其次,您可以编辑打字文件:
- 将
find
更改为filter
并按 F12(转到声明) - 将此行复制到类型文件中并将函数重命名为
find
并将返回值改为单个对象而不是数组! - 保存该文件
- 在您的代码中将您的背部
filter
重命名为find
..
JS中没有findByIndex方法,只有findIndex.
方法您可以使用 filter 或 find 方法按索引获取项目:
// ES2015
selectedCategory = categories.find(item => item.categoryId === 1);
// ES5
selectedCategory = categories.filter(item => item.categoryId === 1)[0];
获取具体的参数值。 使用此代码
this.categories.find(item => item.categoryId === 1).categoryId
Where categoryId 可以是你想要的任何字段