The elements in an array composed of JSON objects are completely deleted in JS

Source: Internet
Author: User

Just share a little knowledge ~

In JS, for an array consisting of a JSON object, for example:

var test = [{"A": "1", "B": "2"}, {"A": "3", "B": "4"}, {"A": "5", "B": "6"}];

What should we do if we want to delete the second JSON object? In fact, the method is exactly the same as the operation array.

At the beginning of the attempt to use the delete operator, but when querying the length of the array, it is found that this method does not completely delete the element, but instead deletes its value, but still retains space.

    var test = [{"A": "1", "B": "2"}, {"A": "3", "B": "4"}, {"A": "5", "B": "6" }];    Test.length   // output is 3    Delete test[1];    Test.length   // output is still 3

Query operator Delete We know that it simply resets the value to undefined without affecting the length of the array, turning it into a sparse array ("JS authoritative guide" section 7.5).

To understand this, perhaps think of the deletion point after the elements can be moved forward 1 units, the implementation of the total elimination of the element, but in the JS method we can find a more convenient way: Splice () method

    var test = [{"A": "1", "B": "2"}, {"A": "3", "B": "4"}, {"A": "5", "B": "6" }];    Test.length   // output is 3    test.splice (1, 1);    Test.length   // output is 2

Test.length becomes 2 after deletion, which is exactly what we want.

We can find a description of the splice () in the information about:

arrayobject.splice (Index, Howmany, Item1, ..., ItemX) method adds/Deletes an item to/from the array, and then returns the item that was deleted.

Parameter 1:index is the starting position for insert additions or (and) deletions;

Parameter 2:howmany Specifies the number of elements added/removed from the array;

Parameter 3:item1, ..., ItemX Optional, select the Add action to fill in, indicating the element that needs to be added.

The elements in an array composed of JSON objects are completely deleted in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.