Reputation: 1514
Hi i am a newbie to Javascript.
i am reading a book where i am learning splice()
method.
Here is my code
var fruits = ["oranges", "apples", "pears", "grapes"];
var somefruits = fruits.splice(2, 1, "watermelons");
for (var i = 0; i < somefruits.length; i++) {
document.write(somefruits[i] + '<br>');
};
Somehow the result is only showing pears. Can someonetell me why the whole array with watermelons is not replaced. Thanks,.
Upvotes: 0
Views: 29
Reputation: 1709
splice will replace the original array and return the values that been replaced. So in your case:
somefruits = fruits.splice(2, 1, "watermelons")
somefruits will be the value been replaced which is ["pear"] and the original fruits value been updated to : ["oranges", "apples", "watermelon", "grapes"]
Upvotes: 2