0
ONE CAN EXPLAIN HOW REMOVED ITEMS OPERATES HERE
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>splice()</h2> <p>The splice() method adds new elements to an array, and returns an array with the deleted elements (if any).</p> <button onclick="myFunction()">Try it</button> <p id="demo1"></p> <p id="demo2"></p> <p id="demo3"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits; function myFunction() { var removed = fruits.splice(2, 2, "Lemon", "Kiwi"); document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits; document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed; } </script> </body> </html>
2 Answers
+ 5
Array.prototype.splice() is an interesting method.
With only one argument.
It removes the array element at the indicated position.
For example,
array1 = ["a", "b", "c"]
array1.splice(1) //removes "b"
array1 is now ["a", "c"]
With two arguments (arg1, arg2) ,
it removes arg2 elements starting at position arg1
For example
array2 = ["d", "e", "f", "g"]
array2.splice(1,2) // removes "e" and "f"
array2 now becomes ["d", "g"]
With more than two arguments, the rest are for inserting at the spliced position, as you have seen in your example.
Lastly, splice() method returns an array of what it removes.
That's why the removed elements of "Apple" and "Mango" is stored in the variable named removed in your example.
+ 3
Batte Fred
In this code there is an array of fruits = ["Banana", "Orange", "Apple", "Mango"];
The splice() method replaces the following two values ââin the fruits array with the second index:
<< fruits[2] = "Apple";
fruits[3] = "Mango" >>
and at the same time assigns them to the array "removed":
 << var removed = fruits.splice (2, 2, "Lemon", "Kiwi"); >>