Get Programming with JavaScript - Listing 8.06
Listing 8.06 - Manipulating arrays with push, pop and join
JS Bin
var items = [];
var item = "The Pyramids";
var removed;
items.push(item);
items.push("The Grand Canyon");
items.push("Bondi Beach");
console.log(items);
removed = items.pop();
console.log(removed + " was removed");
console.log(items.join(" and "));
Further Adventures
Listing 8.06 - Manipulating arrays with push, pop and join - Tasks 1&2
- Push another item onto the array.
- Log the joined items.
var items = [];
var item = "The Pyramids";
var removed;
items.push(item);
items.push("The Grand Canyon");
items.push("Bondi Beach");
console.log(items);
removed = items.pop();
console.log(removed + " was removed");
console.log(items.join(" and "));
items.push("Popocatépetl");
console.log(items.join(" and "));
Listing 8.06 - Manipulating arrays with push, pop and join - Task 3
- Set one of the items using square brackets.
var items = [];
var item = "The Pyramids";
var removed;
items.push(item);
items.push("The Grand Canyon");
items.push("Bondi Beach");
console.log(items);
removed = items.pop();
console.log(removed + " was removed");
console.log(items.join(" and "));
items.push("Popocatépetl");
console.log(items.join(" and "));
// add a fourth item
items[3] = "The Taj Mahal";
// adding an item at the end of the array
// has the same effect as using push
items[items.length] = "The Tower of London";
Listing 8.06 - Manipulating arrays with push, pop and join - Task 4
- Can you push more than one item at a time?
var items = [];
var item = "The Pyramids";
var removed;
items.push(item);
items.push("The Grand Canyon");
items.push("Bondi Beach");
console.log(items);
removed = items.pop();
console.log(removed + " was removed");
console.log(items.join(" and "));
items.push("Popocatépetl");
console.log(items.join(" and "));
items[3] = "The Taj Mahal";
items[items.length] = "The Tower of London";
// push multiple items at once
items.push("Devils Tower", "The Great Wall", "Old Faithful");
console.log(items.join("\n"));