|
| 1 | +var fruits = ["Apple", "Banana"]; |
| 2 | + |
| 3 | +// Loop over an Array |
| 4 | +fruits.forEach(function (item, index, array) { |
| 5 | + console.log(item, index); |
| 6 | +}); |
| 7 | +// Apple 0 |
| 8 | +// Banana 1 |
| 9 | + |
| 10 | +// Add to the end of an Array |
| 11 | +var newLength = fruits.push("Orange"); |
| 12 | +// ["Apple", "Banana", "Orange"] |
| 13 | + |
| 14 | +// Remove from the end of an Array |
| 15 | +var last = fruits.pop(); // remove Orange (from the end) |
| 16 | +// ["Apple", "Banana"]; |
| 17 | + |
| 18 | +// Remove from the front of an Array |
| 19 | +var first = fruits.shift(); // remove Apple from the front |
| 20 | +// ["Banana"]; |
| 21 | + |
| 22 | +// Add to the front of an Array |
| 23 | +var newLength = fruits.unshift("Strawberry") // add to the front |
| 24 | +// ["Strawberry", "Banana"]; |
| 25 | + |
| 26 | +// Find the index of an item in the Array |
| 27 | +fruits.push("Mango"); |
| 28 | +// ["Strawberry", "Banana", "Mango"] |
| 29 | +var pos = fruits.indexOf("Banana"); |
| 30 | +// 1 |
| 31 | + |
| 32 | +// Remove an item by Index Position |
| 33 | +var removedItem = fruits.splice(pos, 1); // this is how to remove an item, |
| 34 | +// ["Strawberry", "Mango"] |
| 35 | + |
| 36 | +// Remove items from an Index Position |
| 37 | +var removedItems = fruits.splice(pos, n); // this is how to remove items, n defines the number of items to be removed, |
| 38 | + // from that position onward to the end of array. |
| 39 | +// let, n = 1; |
| 40 | +// ["Strawberry"] |
| 41 | + |
| 42 | +// Copy an Array |
| 43 | +var shallowCopy = fruits.slice(); // this is how to make a copy |
| 44 | +// ["Strawberry"] |
0 commit comments