Aim of the puzzle: Use the
.splice() array method to insert or replace elements in an array.
Walk through of solution: The
.splice() method is a useful and flexible way to add or replace elements anywhere in an array.
Splice takes 3 arguments when it is called:
- The index number where to insert
- The number of items to replace
- The new items to insert
In this puzzle, the
numbers array begins with 3 elements, the numbers
4. To add the number
2 into the 2nd position, splice is used like this:
numbers.splice(1, 0, 2);
In the above code,
1 is the index position where we want to insert the new element.
0 is the number of items to replace, and
2 is the new element.
Sample code solution:
let numbers = [1, 3, 4]; numbers.splice(1, 0, 2); console.log(numbers);
.splice(), Variable Declarations with Let, console.log