可以使用 TypeScript 中的多种方法来删除数组项。用于实现上述功能的方法是
splice()
、
shift()
、
pop()
和
delete
运算符。
在这篇文章中,我们将介绍几种使用 TypeScript 删除数组项的不同方法。
使用
splice()
删除 TypeScript 中的数组项
在 TypeScript 中删除和添加元素时,
splice()
是最佳选择。
splice()
是最佳选择的主要原因有两个。
array.splice(array_index, no_of_elements, [element1][, ..., elementN]);
let
array
=
[
"white"
,
"yellow"
,
"black"
,
"green"
,
"blue"
];
let
removed
=
array.splice(
3
,
1
,
"red"
);
console.log(
"The new array is : "
+
array );
console.log(
"The color that was removed is : "
+
removed);
The
new
array
is
:
white,yellow,black,red,blue
The color that was removed
is
:
green
使用
shift()
删除 TypeScript 中的数组项
shift()
方法可以从 TypeScript 中的数组中删除一个元素,但它的容量是有限的。使用
shift()
只能删除特定数组的第一个元素并返回它。
此外,它没有需要传递给函数的参数,因为它只执行一项任务。
array.shift();
let
array
=
[
"white"
,
"yellow"
,
"black"
,
"green"
,
"blue"
].shift();
console.log(
"The removed color is : "
+
array );
The removed color
is
:
white
使用
pop()
删除 TypeScript 中的数组项
pop()
具有与
shift()
类似的功能,但两个函数之间的区别在于,
shift()
删除数组的第一个元素,而
pop()
删除数组的最后一个元素并返回它。
array.pop();
let
array
=
[
"white"
,
"yellow"
,
"black"
,
"green"
,
"blue"
].pop();
console.log(
"The removed color is : "
+
array );
The removed color
is
:
blue
使用
delete
运算符删除 TypeScript 中的数组项
TypeScript 中的
delete
运算符完全删除了属性的值和对象的属性,但我们仍然可以使用运算符实现删除元素的功能。该属性在删除后不能再次使用,除非重新添加回来。
不推荐使用
delete
运算符,因为我们可以通过使用
splice()
、
shift(),
和
pop()
的方法以更有效和安全的方式获得相同的结果。
let
array
=
[
"white"
,
"yellow"
,
"black"
,
"green"
,
"blue"
];
delete
array[
1
];
console.log(
"The array after deletion : "
+
array);
The array after deletion :
white
,,black,green,blue
TypeScript 中 No overload matches this call 错误
TypeScript 中如何导出多个类型
{[key: string]: any} 在 TypeScript 中是什么意思
TypeScript 中检查变量的类型
如何在 TypeScript 中导出多个变量
在 TypeScript 中使用索引遍历数组
TypeScript 中的重复函数实现
在 TypeScript 中将字符串转换为数字
在 TypeScript 中使用索引迭代字符串