Category: Variables
Inserts the item into the array at the specified index position.
In real life you sometimes need to add items at various positions in a list, and make the list larger. insertItem(list, index, item) makes the "list" one larger and inserts the "item" at the specified index position (moving other items to the right). The index must be a valid index position in the list or you may get unexpected results.
// List of favorite foods. var myFavoriteFoods=["pizza","steak"]; console.log(myFavoriteFoods + " length=" +myFavoriteFoods.length); insertItem(myFavoriteFoods, 1, "artichokes"); console.log(myFavoriteFoods + " length=" +myFavoriteFoods.length); insertItem(myFavoriteFoods, 4, "shrimp"); console.log((myFavoriteFoods + " length=") +myFavoriteFoods.length);
Example: Fibonacci Generate the first 10 numbers in the fibonacci sequence.
// Generate the first 10 numbers in the fibonacci sequence. var fibonacci=[1,1]; var nextTerm=0; for (var i=3; i<=10; i++) { nextTerm=fibonacci[i-2]+fibonacci[i-3]; insertItem(fibonacci, i, nextTerm); } console.log(fibonacci);
insertItem(list, index, item)
Name | Type | Required? | Description |
---|---|---|---|
list | variable name | Yes | The variable name of the list (array) you want to insert the item into. |
index | number | Yes | The index position you want to insert the item at. |
item | any type | Yes | The number or string item to be inserted into the list. |
No return value.
Found a bug in the documentation? Let us know at documentation@code.org
insertItem(list, index, item)
Found a bug in the documentation? Let us know at documentation@code.org