最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does deleting an element from the array not change the array’s length? - Stack Overflow

programmeradmin0浏览0评论

Why is JavaScript returning the wrong array length?

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

Why is JavaScript returning the wrong array length?

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

Share Improve this question edited Jun 16, 2024 at 8:22 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Jan 21, 2010 at 11:00 user255692user255692
Add a comment  | 

6 Answers 6

Reset to default 13

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)

  1. 暂无评论