Array

  • Arrays: ordered collections of values
    • List of comments on IG post
    • Collection of levels in a game
    • songs in a playlist
  • Creating Arrays
let students = [];  //empty array

let colors = ['red', 'orange', 'yellow']; // strings

let lottoNums = [19,22,34];  //numbers

let stuff = [true, 68, 'cat', null];   //mixed array
  • arrays can be modified
let colors = ['red', 'blue', 'green'];

color[0] = 'red';

color[3] = 'blue';
  • Array methods
    • push, add to end
    • pop, remove from end
    • shift, remove from start
    • unshift, add to start
    • concat, merge arrays
    • includes, look for a value
    • indexOf, just like string.indexOf
    • join, creats a string from an array
    • reverse, reverses an array
    • slice, copies a portion on an array
    • splice, removes/replaces elements
    • sort, sort an array
  • Use const to define an array, as long as the reference remains the same, we can change the values of an array
  • const Eggs = ['brown', 'brown'];
    Eggs.push('purple');
    Eggs[0] = 'green';
    
    
    
    Eggs = ['nlue', 'pink']; //ERROR ! the reference was changed
  • nested arrays

    const board = [
         ['O', null, 'X'],
         ['H', 'A', 'N'],    
    ]
    
    
    board[1][0] = 'H'
原文地址:https://www.cnblogs.com/LilyLiya/p/14249739.html