Home >Web Front-end >JS Tutorial >How Can I Insert Elements into JavaScript Arrays at Specific Indices?
JavaScript arrays naturally lack an intuitive insert method. However, a compelling solution exists through the native array function splice.
The splice function takes three arguments:
To insert an element at a specific index, use the following syntax:
arr.splice(index, 0, item);
This inserts the item into the array at the index, without deleting any existing elements.
Consider the following JavaScript code:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge arr.splice(2, 0, "Lene"); console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
In this example:
The above is the detailed content of How Can I Insert Elements into JavaScript Arrays at Specific Indices?. For more information, please follow other related articles on the PHP Chinese website!