In: Computer Science
In javascript, Add a method named insertStep that receives a String and an int. It adds the String to the collection of instructions, before the step whose index is the int. You may assume that the user won’t try to insert something before a step that doesn’t exist.
To achieve this task I have used array.splice().
Syntax for the above function is :
array.splice(index, no_of_items_to_remove, item1 ... itemX)
The only insertion can be done by specifying the number of elements to be deleted to 0. This allows to only insert the specified item at a particular index with no deletion.
So, Now move to our code :
Code:
function insertStep(newInstruction, index){
Instructions.splice(index, 0, newInstruction);
}
var Instructions = ["first step", "second step", "third step", "fourth step", "fiifth step", "sixth step", "seventh step"];
insertStep("addNew", 2)
Output for a sample testcase:
You can see, I specified index 2, so it our function added new Instruction at index 2.
Try running this code on your own system.
Like, if this helped :)