Aim of the puzzle: Use the .splice()
array method to replace an element in an array with a new element.
Walk through of solution: .splice()
is one of the more flexible array methods, as it can be used to add or remove elements to an array. It takes 3 arguments:
- The index to start selecting
- The number of items to replace. If 0, splice will not replace any items
- The new item(s) to insert
For example, in the following code:
['cheese', 'tomato', 'bread'].splice(1, 1, 'eggs');
// This will replace 'tomato' with 'eggs'
This will start at index 1
, remove 1 element, and add the string 'eggs'
to the array.
To complete the puzzle, use .splice()
on the mice
array to replace 1 or more of the elements with a new string.
Sample code solution:
import { mice } from 'grasshopper.mousePad';
mice.splice(1, 1, 'Jerry');
for (let mouse of mice) {
console.log(mouse);
}
Javascript Concepts: Arrays, Array Methods, .splice()
, For of Loops, console.log()
, Import Declarations
Additional Code (hidden code that runs before the puzzle’s code):
let mice = ['Minnie', 'Tom', 'Fievel', 'Pinky']