JavaScript truncates an array by setting the length attribute of the array. It is the only method to shorten the length of the array. if you use the delete operator to delete elements in an array, although the element becomes undefined, The length attribute of the array does not change the two ways to delete elements, and the length of the array also changes.
<Script>
/*
* Method: Array. remove (dx)
* Function: delete an array element.
* Parameter: dx deletes the subscript of an element.
* Return value: Modify the array on the original array.
*/
// It is often used to reconstruct the array through traversal.
Array. prototype. remove = function (dx)
{
If (isNaN (dx) | dx> this. length) {return false ;}
For (var I = 0, n = 0; I <this. length; I ++)
{
If (this [I]! = This [dx])
{
This [n ++] = this [I]
}
}
This. length-= 1
}
A = [1, 2, 3, 4, 5];
Alert ("elements:" + a + "Length:" + a. length );
A. remove (0); // Delete the element whose subscript is 0
Alert ("elements:" + a + "Length:" + a. length );
/*
* Method: Array. baoremove (dx)
* Function: delete an array element.
* Parameter: dx deletes the subscript of an element.
* Return value: Modify the array on the original array.
*/
// We can also use splice.
Array. prototype. baoremove = function (dx)
{
If (isNaN (dx) | dx> this. length) {return false ;}
This. splice (dx, 1 );
}
B = [1, 2, 3, 4, 5];
Alert ("elements:" + B + "Length:" + B. length );
B. baoremove (1); // Delete the element whose subscript is 1.
Alert ("elements:" + B + "Length:" + B. length );
</Script>