首页 文章

如何在TypeScript中删除数组项?

提问于
浏览
204

我有一个我在TypeScript中创建的数组,它有一个我用作键的属性 . 如果我有该密钥,我该如何从中删除一个项目?

7 回答

  • 1

    使用Typescript的另一个解决方案:

    let updatedArray = [];
    for (let el of this.oldArray) {
        if (el !== elementToRemove) {
            updated.push(el);
        }
    }
    this.oldArray = updated;
    
  • 12

    与在JavaScript中一样 .

    delete myArray[key];
    

    请注意,这会将元素设置为 undefined .

    最好使用Array.prototype.splice函数:

    const index = myArray.indexOf(key, 0);
    if (index > -1) {
       myArray.splice(index, 1);
    }
    
  • 349

    如果array是对象的类型,那么最简单的方法是

    let foo_object // Item to remove
    this.foo_objects = this.foo_objects.filter(obj => obj !== foo_object);
    
  • 2

    使用ES6,您可以使用以下代码:

    removeDocument(doc){
       this.documents.forEach( (item, index) => {
         if(item === doc) this.documents.splice(index,1);
       });
    }
    
  • 90

    这是我的解决方案:

    onDelete(id: number) {
        this.service.delete(id).then(() => {
            let index = this.documents.findIndex(d => d.id === id); //find index in your array
            this.documents.splice(index, 1);//remove element from array
        });
    
        event.stopPropagation();
    }
    
  • 19

    您可以在数组上使用 splice 方法来删除元素 .

    例如,如果您有一个名为 arr 的数组,请使用以下命令:

    arr.splice(2,1);
    

    所以这里索引2的元素将是起点,参数2将确定要删除的元素数量 .

    如果要删除名为 arr 的数组的最后一个元素,请执行以下操作:

    arr.splice(arr.length,1);
    

    这将返回arr并删除最后一个元素 .

  • 8

    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;
    

相关问题