Sunday, March 18, 2018

javascript - How to "push' a new item to the middle of an array?

I just completed section1, and noticed that there isn't a method covered on how to push an item to the a specific location of the array. For example, if I wanted the array to show



var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]


How would I be able to push in "Brooks Brothers" into the position [2] of the array suits, and shift the rest 1 down? Is there a built-in function in javascript similar to push that would enable me to do this?




I suppose I could always, with some diffculty:



function add (item, position){
var length = suits.length;
for(i = length -1; i >= position; i--){
suits[length] = suits[i];
length--;
};
suits[position] = item;

};

add("Brooks Brothers",2) //to add it to the middle

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...