Here, we use arrays in JS to create objects like generics and hash tables.
I. Create
Create an object with the name and age columns. The creation method is as follows: VaR Arr = New Array ();
// Use array to create an array
Function Funarraylist (){
Arr [ 0 ] = {Name: " N1 " , Age: " 10 " }; // Add object 1
Arr [ 1 ] = {Name: " N2 " , Age: " 11 " }; // Add object 2
Arr. Sort ();
// Show all objects
For ( VaR J = 0 ; J < Arr. length; j ++ ){
Alert (ARR [J] [ ' Name ' ] + " - " + Arr [J] [ ' Age ' ]);
}
}
Result:
N2-11
N1-10
Ii. Delete
DeleteSpliceMethod.
// Use array to delete values in an array
Function Funarraylistdel (){
If (ARR. Length > 0 ){
For ( VaR J = 0 ; J < Arr. length; j ++ ){
// Delete a specified value
If (ARR [J] [ ' Name ' ] = " N1 " ){
Alert ( " Deleted " + Arr [J] [ ' Name ' ] + " - " + Arr [J] [ ' Age ' ]);
// Delete
Arr. splice (J, 1 );
}
}
// Display deleted results
For ( VaR J = 0 ; J < Arr. length; j ++ ){
Alert (ARR [J] [ ' Name ' ] + " - " + Arr [J] [ ' Age ' ]);
}
}
}
result:
deleted n1-10
n2-11
Note: splice () usage
definition and usage
the splice () method is used to insert, delete, or replace elements in an array.
syntax
arrayobject. splice (index, howmany, element1 ,....., elementx)
parameter |
description |
index |
required. Specifies where to add/delete elements. this parameter is the subscript of the array element to be inserted and/or deleted, must be a number. |
howmany |
required. Specifies how many elements should be deleted. It must be a number, but it can be "0 ". if this parameter is not specified, then, all elements starting from index to the end of the original array are deleted. |
element1 |
optional. Specifies the new element to be added to the array. Insert from the subscript indicated by index. |
elementx |
optional. You can add several elements to an array |
Return Value
If an element is deleted from an arrayobject, an array containing the deleted element is returned.
Description
The splice () method deletes zero or multiple elements starting from the index and replaces the deleted elements with one or more values declared in the parameter list.
Tips and comments
Note:Note that the splice () method and slice () method have different functions. The splice () method directly modifies the array.