How do I remove an array item in TypeScript?

后端 未结 14 2342
渐次进展
渐次进展 2020-12-07 07:42

I have an array that I\'ve created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?

14条回答
  •  余生分开走
    2020-12-07 07:57

    You can use the splice method on an array to remove the elements.

    for example if you have an array with the name arr use the following:

    arr.splice(2, 1);
    

    so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted.

    If you want to delete the last element of the array named arr then do this:

    arr.splice(arr.length-1, 1);
    

    This will return arr with the last element deleted.

    Example:

    var arr = ["orange", "mango", "banana", "sugar", "tea"];
    arr.splice(arr.length-1, 1)
    console.log(arr); // return ["orange", "mango", "banana", "sugar"]
    

提交回复
热议问题