文章内容
2022/1/13 18:29:30,作 者: 黄兵
Typescript 列表删除与字典操作
下面有一个这样的 Array:
this.tags=[{id: 1, linkText: 'crawler', tag: '爬虫'},{id: 4, linkText: 'python', tag: 'Python'}]
我们要实现如下效果:删除 tag 为“爬虫”的元素,也就是:{id: 1, linkText: 'crawler', tag: '爬虫'}
首先我们要遍历每一个元素:
let index: number;
this.tags.forEach((value, idx) => {
if (value['tag'] === tag) {
index = idx;
}
});
上面循环使用的是 forEach,是为了获取索引:
const someArray = [9, 2, 5]; someArray.forEach((value, index) => { console.log(index); // 0, 1, 2 console.log(value); // 9, 2, 5 });
同时我们再 Typescript 为了获取字典的值,使用如下的方式:
value['key']
如果我们需要设置字典的值,可以使用下面的方式:
let dictionaryViaLiteral = { 'firstName': 'Gapur', 'lastName': 'Kassym', 'country': 'Kazakhstan' }; // Using bracket dictionaryViaLiteral['firstName'] = 'New Name'; // Using directly by property name via dot dictionaryViaLiteral.firstName = 'Tom';
当然我们也可以用这种方式获取字典的值:
// Using bracket/indexer const firstName = dictionaryViaLiteral['firstName']; // Using directly by property name via dot const firstName = dictionaryViaLiteral.firstName;
上面首先获取“爬虫”所在的元素索引,索引值为 index
if (index >= 0) { this.tags.splice(index, 1); }
如果值不存在 index 会等于 -1
这样就再 Typescript 完成了对 Array 的删除。
参考资料:
1、TypeScript for ... of with index / key?
2、How do I remove an array item in TypeScript?
3、Building a type-safe dictionary in TypeScript
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - Typescript 列表删除与字典操作
评论列表