Javascript数组问题

Javascript数组问题,javascript,arrays,Javascript,Arrays,为什么JavaScript返回错误的数组长度 var myarray = ['0','1']; delete myarray[0]; alert(myarray.length); //gives you 2 必须使用array.splice-请参见 然后,根据delete操作符,删除第一个元素,但不更改数组的长度。您可以使用splice()。来自Array的MDC文档: 删除数组元素时 数组长度不受影响。对于 例如,如果删除[3],则会删除[4] a[4]和a[3]仍然没有定义 即使删除最后一

为什么JavaScript返回错误的数组长度

var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2

必须使用array.splice-请参见


然后,根据delete操作符,删除第一个元素

,但不更改数组的长度。您可以使用splice()。

来自Array的MDC文档:

删除数组元素时 数组长度不受影响。对于 例如,如果删除[3],则会删除[4] a[4]和a[3]仍然没有定义 即使删除最后一个,也会保留 数组的元素(删除 a[a.length-1])

删除”不会修改数组,但会修改数组中的元素:

 # x = [0,1];
 # delete x[0]
 # x
 [undefined, 1]

你需要的是这是正常的行为。函数的作用不是删除索引,而是删除索引的内容。因此,数组中仍有2个元素,但在索引0处,将有
未定义的

可以使用的nice remove()方法执行此操作:


对其他代码也会删除该项。但它不会更新长度。
 # x = [0,1];
 # delete x[0]
 # x
 [undefined, 1]
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);