添加删除元素方法
作者:jcLee95:https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343
邮箱:291148484@163.com
本文地址:https://blog.csdn.net/qq_28550263/article/details/121710541
1. 引言:没有依索引删除元素的JavaScript数组(Array)
1. 引言:没有依索引删除元素的JavaScript数组(Array)
在JavaScript数组中,直接使用delete
关键字删除数组中的一个元素是会产生空位的。比如:
var a = [0,1,2,3,4,5,6]
delete a[2]
console.log(a);
NodeJS-OutPut[]:
[ 0, 1, <1 empty item>, 3, 4, 5, 6 ]
这表明,该方法仅仅是将索引处对应元素的值给抹掉了(成了udefined
),除此之外数组还是那个数组,就连长度都没变。因此算不上真正意义的删除。
2. 删除一个动态数组需要完成的事情
这里必须区分一些动态链表表示的数组,由于链表是由节点构成的,其删除中间的某个元素只需将删除处前一个结点的后继指向删除处的后继节点。(如果是双链表还需要修改原后继的前驱指针)
但是JavaScript的数组不是基于链表实现的,其删除中间某个索引处元素后必须逐个移动后面的元素,最后将先前最后一个空位所占用的空间释放出来。
因此,要让JavaScript数组删除后得到一个我们一般期待的新数组,需要做这三件事:
- 删除索引处的元素;
- 将后面的元素依次前移以填补空位;
- 从数组中弹出原最后一个元素。
3. 代码实现
通过 ES 6 类的语法实现如下:
class List extends Array{
drop(index){
delete this[index];
for(let i=index;i<this.length-index+1;i++){
this[i] = this[i+1];
}
this.pop()
}
}
使用方式:
let a = new List(0,1,2,3,4,5,6)
console.log('删除元素前:');
console.log(a);
console.log(a.length);
a.drop(2)
console.log('删除元素后:');
console.log(a);
console.log(a.length);
NodeJS-OutPut[]:
删除元素前:
List(7) [
0, 1, 2, 3,
4, 5, 6
]
7
删除元素后:
List(6) [ 0, 1, 3, 4, 5, 6 ]
6
如果使用的是TypeScript
,请添加类型注释:
不限制类型:
class List extends Array{
drop(index){
delete this[index];
for(let i=index;i<this.length-index+1;i++){
this[i] = this[i+1];
}
this.pop()
}
}
限制类型:
class List<T> extends Array<T>{
drop(index:number){
delete this[index];
for(let i=index;i<this.length-index+1;i++){
this[i] = this[i+1];
}
this.pop()
}
}
附: tsc编译
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var List = /** @class */ (function (_super) {
__extends(List, _super);
function List() {
return _super !== null && _super.apply(this, arguments) || this;
}
List.prototype.drop = function (index) {
delete this[index];
for (var i = index; i < this.length - index + 1; i++) {
this[i] = this[i + 1];
}
this.pop();
};
return List;
}(Array));