How do I remove an array item in TypeScript?

后端 未结 14 2304
渐次进展
渐次进展 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 08:05

    Answer using TypeScript spread operator (...)

    // Your key
    const key = 'two';
    
    // Your array
    const arr = [
        'one',
        'two',
        'three'
    ];
    
    // Get either the index or -1
    const index = arr.indexOf(key); // returns 0
    
    
    // Despite a real index, or -1, use spread operator and Array.prototype.slice()    
    const newArray = (index > -1) ? [
        ...arr.slice(0, index),
        ...arr.slice(index + 1)
    ] : arr;
    

提交回复
热议问题