|
| 1 | +// node arrays.js |
| 2 | + |
| 3 | +'use strict' |
| 4 | +console.log('// Array literals are enclosed in square brackets') |
| 5 | +const numbers = [1, 2, 3, 'many'] |
| 6 | +console.log('numbers:', numbers) // [1, 2, 3, 'many'] |
| 7 | +console.log('// An array can have missing elements') |
| 8 | +const someNumbers = [ , 2, , 9] // No properties '0', '2' |
| 9 | +console.log('someNumbers:', someNumbers) // [<1 empty item>, 2, <1 empty item>, 9] |
| 10 | +console.log('// You can add new elements past the end') |
| 11 | +someNumbers[6] = 11 // Now someNumbers has length 7 |
| 12 | +console.log('someNumbers:', someNumbers) // [<1 empty item>, 2, <1 empty item>, 9, <2 empty items>, 11] |
| 13 | +console.log('// A trailing comma does not indicate a missing element') |
| 14 | +const developers = [ |
| 15 | + 'Harry Smith', |
| 16 | + 'Sally Lee', |
| 17 | + // Add more elements above |
| 18 | +] |
| 19 | +console.log('developers:', developers) // ['Harry Smith', 'Sally Lee'] |
| 20 | +console.log('// Since arrays are objects, you can add arbitrary properties') |
| 21 | +numbers.lucky = true |
| 22 | +console.log('numbers:', numbers) // [1, 2, 3, 'many', lucky: true] |
| 23 | +console.log('// Converting an array to a string') |
| 24 | +const str = '' + [1, 2, 3] |
| 25 | +console.log('str:', str) // 1,2,3 |
| 26 | +console.log('// A two-dimensional array is an array of arrays') |
| 27 | +const melancholyMagicSquare = [ |
| 28 | + [16, 3, 2, 13], |
| 29 | + [5, 10, 11, 8], |
| 30 | + [9, 6, 7, 12], |
| 31 | + [4, 15, 14, 1] |
| 32 | +] |
| 33 | +console.log('melancholyMagicSquare:', melancholyMagicSquare) // [[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]] |
| 34 | +console.log('// Use two brackets to access an element') |
| 35 | +const element = melancholyMagicSquare[1][2] // 11 |
| 36 | +console.log('element:', element) |
0 commit comments