我正在尝试使用此说明从数组中删除元素:
使用循环移位数组值,如下所示。从index参数开始;对于小于长度的索引 - 将一个索引移向末尾 将当前索引处的数组值设置为以下索引处的数组值
Example: remove value at index 2 in List: a b c d e
0 1 2 3 4
before loop: a b c d e
after loop pass 1: a b d d e (index 2 copies 'd' from index 3)
after loop pass 2: a b d e e (index 3 copies 'e' from index 4)
(loop ends)
将数组长度减少一个;在JavaScript中,这会从数组中删除最后一个元素。
为什么我的代码无效?
this._data = ["a", "b", "c", "d", "e"];
length() {
return this._data.length;
}
remove(index) {
if (index === this.length()) {
delete this._data[this.length()];
}
while (index < this.length()) {
this._data[index] = this._data[index + 1];
index++;
}
delete this._data[this.length() - 1];
}
答案 0 :(得分:0)
你的代码很糟糕,你不能在没有属性的东西上使用属性.length你应该初始化对象并在(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)
C#
或
var arr = ["a", "b", "c", "d", "e"];
arr.splice(2, 1); /* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice */
/* ["a", "b", "d", "e"] */