简体   繁体   English

从 Typescript 中的数组中删除项目 Using.filter() - 不可变模式

[英]Removing Items from an Array in Typescript Using .filter() - Immutable Pattern

I am trying to remove item from array Using.filter() - Immutable Pattern我正在尝试从数组中删除项目 Using.filter() - 不可变模式

const drinks = ['Cola', 'Lemonade', 'Coffee', 'Water'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink !== idx);

But the problem I have that I have error like this但是我遇到的问题是我有这样的错误

const idx: number This condition will always return 'true' since the types 'string' and 'number' have no overlap const idx: number 此条件将始终返回“true”,因为类型“string”和“number”没有重叠

With .filter 's callback, the first argument is the value being iterated over, and the second argument is the index being iterated over.对于.filter的回调,第一个参数是被迭代的值,第二个参数是被迭代的索引。 TypeScript is correctly warning you that comparing the idx - a number - to one of the array elements - a string - doesn't make sense. TypeScript 正确地警告您将idx - 一个数字 - 与数组元素之一 - 一个字符串 - 进行比较没有意义。

indexOf is completely superfluous anyway here. indexOf在这里是完全多余的。 Just use只需使用

const drinks = ['Cola', 'Lemonade', 'Coffee', 'Water'];
const id = 'Coffee';
const filteredDrinks = drinks.filter(drink => drink !== id);

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

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