During the interview, if the examiner asks you to use JavaScript to insert, delete, and replace array elements. If you do not know the method used by Array. prototype. splice, the score may be deducted. Using the built-in splice method of javascript array type, you can insert, delete, and replace array elements with only one line of code.
Method signature:
Array. prototype. splice (index, count [, elm1, elm2... n])
Description:
Array splice can be used to insert, replace, and delete Array elements. This method directly affects the current array object (different from the. slice (index1, index2) method) and returns the deleted array items.
Parameters:
Index: the starting subscript of the element in the array.
Count: number of elements to be deleted or replaced.
Elems: The items to be inserted into the array.
Return Value: return the items removed from the group.
Demo:
Var items = ["a", "B", "c", "d", "e"];
// Delete an element
Result = items. splice (1, 2)
// This operation deletes the element ["B", "c"] in the items array in the example, and returns ["B", "c"] to result.
// Replace Element
Result = items. splice (1, 2, "x", "y ")
// This operation uses the element "x" and "y" to replace the element ["B", "c"] in the items array in the example, and returns ["B ", "c"] to result.
// Insert element
Result = items. splice (1, 0, "x", "y ")
// The result of this operation is to insert ["x", "y"] after the "B" element of the items array in the example. The return value is null.