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

javascript - Length unchanged after using delete - Stack Overflow

programmeradmin3浏览0评论

I have a function which deletes from an object array but when i check it's .length its the same..

This is what i have:

console.log(data.length);

delete(data[i]);

console.log(data.length);
console.log(data);

My outputs end up like this:

3
3
[object Array]

I have attatched the image of the object array below, you see only 2 entires but the length is still 3.

The initial data im testing with is this:

[
  {"equip":"0","name":"Test","id":"10"},
  {"equip":"0","name":"Test","id":"4"},
  {"equip":"0","name":"Test","id":"5"}
]

You can see my browser has deleted one from the object array.. so why does it still count 3, and how do I fix that so it counts correctly?

I have a function which deletes from an object array but when i check it's .length its the same..

This is what i have:

console.log(data.length);

delete(data[i]);

console.log(data.length);
console.log(data);

My outputs end up like this:

3
3
[object Array]

I have attatched the image of the object array below, you see only 2 entires but the length is still 3.

The initial data im testing with is this:

[
  {"equip":"0","name":"Test","id":"10"},
  {"equip":"0","name":"Test","id":"4"},
  {"equip":"0","name":"Test","id":"5"}
]

You can see my browser has deleted one from the object array.. so why does it still count 3, and how do I fix that so it counts correctly?

Share Improve this question asked Dec 27, 2013 at 4:29 SirSir 8,27717 gold badges88 silver badges154 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

The delete operator deletes a property from an object. In your case, property i. Properties in an array are actually indexes 0 through array.length - 1. Use splice instead:

data.splice(i, 1);

To find out the number of properties in an object, use Object.keys:

Object.keys(data).length will result in 2

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/delete

delete is used to remove element from object for array use splice

array.splice(index, 1);
发布评论

评论列表(0)

  1. 暂无评论