|
| 1 | +/* 1. Arrays |
| 2 | +
|
| 3 | +(i) Declaring Array, */ |
| 4 | +const myArr = [0, 1, 2, 3, 4] |
| 5 | +// console.log(myArr[2]); // Output: 2 | Accsessing value of an Array. |
| 6 | +// Note: Array indexing starts from Zero. |
| 7 | +const heros = ["Thor", "IronMan", "SpiderMan"] |
| 8 | +// console.log(heros); // Output: [ 'Thor', 'IronMan', 'SpiderMan' ] |
| 9 | +const myArr2 = new Array(1, 2, 3, 4) |
| 10 | +// console.log(myArr2); // Output: [ 1, 2, 3, 4 ] |
| 11 | +/* Note: Run const numbers = [1, 2, 3, 4] in browser's console to see prototype access in Arrays. |
| 12 | +
|
| 13 | +----------------------------------------------------------------------------------------------------- |
| 14 | +
|
| 15 | +(ii) Array Methods, */ |
| 16 | +myArr.push(6) |
| 17 | +// console.log(myArr); // Output: [ 0, 1, 2, 3, 4, 6 ] | Pushes element in the end of the array. |
| 18 | +myArr.pop() |
| 19 | +// console.log(myArr); // Output: [ 0, 1, 2, 3, 4 ] | Removes element from the end of the array. |
| 20 | +myArr.unshift(9) |
| 21 | +// console.log(myArr); // Output: [ 9, 0, 1, 2, 3, 4 ] | Adds element to the starting of the array. |
| 22 | +myArr.shift() |
| 23 | +// console.log(myArr); // Output: [ 0, 1, 2, 3, 4 ] | Removes element from the starting of the array. |
| 24 | + |
| 25 | +// console.log(myArr.includes(9)); // Output: false |
| 26 | + |
| 27 | +// console.log(myArr.indexOf(4)); // Output: 4 |
| 28 | +// Note: Indexing starts from Zero. |
| 29 | +// console.log(myArr.indexOf(9)); // Output: -1 |
| 30 | +// Asking any value which doesn't exist in index gives you -1. |
| 31 | + |
| 32 | +const newArr = myArr.join() |
| 33 | +// console.log(newArr); // Output: 0,1,2,3,4 |
| 34 | +// console.log(typeof newArr); // Output: string |
| 35 | +/* Note: .join binds and converts array into strings. |
| 36 | +
|
| 37 | +----------------------------------------------------------------------------------------------------- |
| 38 | +
|
| 39 | +(iii) slice, splice (Methods) */ |
| 40 | +console.log("A ", myArr); // Output: A [ 0, 1, 2, 3, 4 ] |
| 41 | +const myNewArr1 = myArr.slice(1, 3) /* Include value at index 1 and 2 but don't |
| 42 | +include value at index 3. */ |
| 43 | +console.log(myNewArr1); // Output: [ 1, 2 ] |
| 44 | +console.log("B ", myArr); // Output: B [ 0, 1, 2, 3, 4 ] |
| 45 | +// Note: As we can see using slice doesn't affect original array. |
| 46 | + |
| 47 | +const myNewArr2 = myArr.splice(1, 3) |
| 48 | +console.log(myNewArr2); // Output: [ 1, 2, 3 ] |
| 49 | +console.log("C ", myArr); // Output: C [ 0, 4 ] |
| 50 | +// Note: But in splice we can see it removes the elements and manipulates the original array. |
| 51 | + |
0 commit comments