开发者

Javascript Array Problem

Why is JavaScript returning the wrong array length?

var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length);开发者_如何学编程 //gives you 2


The "delete" doesn't modify the array, but the elements in the array:

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

What you need is array.splice


you have to use array.splice - see http://www.w3schools.com/jsref/jsref_splice.asp

myarray.splice(0, 1);

this will then remove the first element


According to this docs the delete operator does not change the length ofth earray. You may use splice() for that.


From Array's MDC documentation:

"When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1])."

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array


You can do this with John Resig's nice remove() method:

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);
};

than

// 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);


That's the normal behavior. The delete() function does not delete the index, only the content of the index. So you still have 2 elements in the array, but at index 0 you will have undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜