简体   繁体   中英

TypeScript: Splice Value from array throws Error

I want to remove a Value from an array.

My Code is runnign fine, but Visual Studio Code indicates that there is a Problem:

My Code:

 removeFromFav(){ var favoritesArray: Array<any> = this.getFavorites() for(let key in favoritesArray){ if(favoritesArray[key].hidx === this.hidx && favoritesArray[key].kontenrahmen === this.kontenrahmen ) { favoritesArray.splice(key, 1); } } localStorage.setItem( this.storageName, JSON.stringify(favoritesArray) ); }

Error Message:

No overload matches this call. Overload 1 of 2, '(start: number, deleteCount?: number | undefined): any[]', gave the following error. Das Argument vom Typ "string" kann dem Parameter vom Typ "number" nicht zugewiesen werden. Overload 2 of 2, '(start: number, deleteCount: number, ...items: any[]): any[]', gave the following error. Das Argument vom Typ "string" kann dem Parameter vom Typ "number" nicht zugewiesen werden.

The Problems seems to be the "key" in line 5 But how can I solve that?

Thanks in advance:)

You are getting error because the syntax is not correct. The following is syntax:

let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

You can mention the start index, delete count: number of items to deleted and item1..itemN: To be added in the array.

You should specify the something like below:

favoritesArray.splice(parseInt(itemIndex), 1);

Since for..in returns key in string type and not number, you should parse to number and then use.

For more details, please refer documentation here arraysplice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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