In JS, for an array composed of JSON objects, for example:

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

If we want to delete the second JSON object, what should we do? Actually, the method is exactly the same as operating on an array.

 

At the beginning, I tried usingdeleteoperator, but when checking the array length, I found that this method does not completely delete the element; instead, it deletes its value while still retaining the space.

var test = [{ "a": "1", "b": "2" }, { "a": "3", "b": "4" }, { "a": "5", "b": "6" }];
test.length   //输出为 3
delete test[1];
test.length   //输出仍为 3

Looking up the delete operator, we know that it only sets that value to undefined and does not affect the array length, i.e., it turns it into a sparse array (Section 7.5 of "JavaScript: The Definitive Guide").

 

Knowing this, perhaps you might think of moving each element after the deletion point forward by one unit to completely remove that element, but in JS methods we can find a simpler approach:splice() method

var test = [{ "a": "1", "b": "2" }, { "a": "3", "b": "4" }, { "a": "5", "b": "6" }];
test.length   //输出为 3
test.splice(1, 1);
test.length   //输出为 2

After deletion, test.length becomes 2, which is exactly the result we want.

Original URL: https://blog.csdn.net/WI_232995/article/details/77776433