SoFunction
Updated on 2025-03-03

Method for deleting elements in built-in JScript object Array

We know that JScript provides us with a built-in array object Array. In addition to providing constructor, length and prototype, the Array object also provides 13 methods by default: concat, join, pop, push, reverse, shift, slice, sort, splice, toLocaleString, toString , unshift and valueOf, but no delete method is provided.

If you are familiar with JavaScript, you will immediately say that the system provides a delete operation that can be used to delete elements in the array. Yes, there is indeed a delete in the JS system that can delete elements in the array. However, this deletion is difficult to use. It can indeed delete elements, but it does not update the element counter of the Array object. For example, we execute:

var ary = ['a', 'b', 'c'];
delete ary[1];
If the deletion is performed correctly, we hope to get a new array, which has two elements ['a', 'c'], with a length of 2. But after execution, we did get an array of two elements ['a', 'c'], but the length of this new array is still 3!. At the same time, we will get "a,,c", which also indicates that the counter of the array is still 3, because Array's toString() actually executes (',').

Such deletion will be very depressed when we use for(; ; ) to traverse the array, and we may easily be killed by an undefined value. So how can I get the size of the synchronized array after deleting the array elements? Since Array itself provides two functions that pop and shift can "really" delete elements of the array, we can use them to expand a remove function ourselves.

However, pop and shift can only delete elements from both ends of the array, so before we delete it, we need to sort out the array, and the code to implement the remove method is as follows:

 = function(obj)
{
    for ( var i=0 ; i <  ; ++i )
    {
        if ( this[i] == obj )
        {
            if ( i > /2 )
            {
                for ( var j=i ; j < -1 ; ++j )
                {
                    this[j] = this[j+1];
                }
                ();
            }
            else
            {
                for ( var j=i ; j > 0 ; --j )
                {
                    this[j] = this[j-1];
                }
                ();
            }    
            break;
        }
    }
};
The purpose of moving and sorting the array is to delete elements and not change the relative positions of the remaining elements. Otherwise, you only need to swap the elements that need to be deleted to pop or shift at both ends.