我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
可以在数组上使用splice方法删除元素。
例如,如果你有一个名为arr的数组,使用以下方法:
arr.splice(2, 1);
因此,这里索引为2的元素将是起点,参数2将决定删除多少个元素。
如果你想删除名为arr的数组的最后一个元素,那么这样做:
arr.splice(arr.length-1, 1);
这将返回删除最后一个元素的arr。
例子:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
其他回答
如果你需要从数组中删除一个给定的对象,并且你想确定以下情况,请使用此方法:
列表没有重新初始化 正确更新数组长度
const objWithIdToRemove;
const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
if (objIndex > -1) {
this.objectsArray.splice(objIndex, 1);
}
和在JavaScript中一样。
delete myArray[key];
注意,这将元素设置为undefined。
最好使用Array.prototype.splice函数:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}
只是想为数组添加扩展方法。
interface Array<T> {
remove(element: T): Array<T>;
}
Array.prototype.remove = function (element) {
const index = this.indexOf(element, 0);
if (index > -1) {
return this.splice(index, 1);
}
return this;
};
可以在数组上使用splice方法删除元素。
例如,如果你有一个名为arr的数组,使用以下方法:
arr.splice(2, 1);
因此,这里索引为2的元素将是起点,参数2将决定删除多少个元素。
如果你想删除名为arr的数组的最后一个元素,那么这样做:
arr.splice(arr.length-1, 1);
这将返回删除最后一个元素的arr。
例子:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
使用TypeScript扩展运算符(…)
// 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;