TIL - Javascript - Array, Elements

홍예찬·2020년 7월 27일
0
post-thumbnail

1. Array(배열)

  • 배열 내부에는 각기 다른 요소(elements)가 포함되어 있다.
const hobbies = ['Watching Netflix', 'Reading books', 'Take a walk'];
console.log(hobbies);
//Output: [ 'Watching Netflix', 'Reading books', 'Take a walk' ]

2. Accessing Elements

const famousSayings = 
      ['Fortune favors the brave.', 
       'A joke is a very serious thing.', 
       'Where there is love there is life.'];
const listItem = famousSayings[0]; 
console.log(listItem); 
//Output: Fortune favors the brave.
console.log(famousSayings[2]); 
//Output: Where there is love there is life.
console.log(famousSayings[3]); //Output: undefined

3. Update Elements

let groceryList = ['bread', 'tomatoes', 'milk'];
groceryList[1] = 'avocados'; 
console.log(groceryList);
//Output: [ 'bread', 'avocados', 'milk' ]

4. Arrays with let and const

let 변수 선언 방식은 array 안의 elements를 변경할 수 있고, 재할당도 가능
const 변수 선언 방식은 array 안의 elements를 변경할 수 있지만 새로운 배열이나 재할당은 불가.

let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];

const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];

condiments[0] = 'Mayo'; 
console.log(condiments);
//Output: [ 'Mayo', 'Mustard', 'Soy Sauce', 'Sriracha' ]
condiments = ['Mayo'];
console.log(condiments);
//Output: [ 'Mayo' ]
utensils[3] = 'Spoon';
console.log(utensils);
//Output: [ 'Fork', 'Knife', 'Chopsticks', 'Spoon' ]

5. The .length property

const objectives = 
      ['Learn a new languages', 'Read 52 books', 'Run a marathon'];
console.log(objectives.length);
//Output: 3

6. Array and Functions

const concept = ['arrays', 'can', 'be', 'mutated'];

function changeArr(arr){
  arr[3] = 'MUTATED';
}
changeArr(concept);
console.log(concept); //Output: [ 'arrays', 'can', 'be', 'MUTATED' ]

function removeElement(newArr) {
  newArr.pop();
}
removeElement(concept);
console.log(concept); //Output: [ 'arrays', 'can', 'be' ]

7. Nested arrays

  • 한 배열에 다른 배열이 포함되어 있는 경우
const numberClusters = [[1, 2], [3, 4], [5, 6]];
const target = numberClusters[2][1];
console.log(target);
//Output: 6
profile
내실 있는 프론트엔드 개발자가 되기 위해 오늘도 최선을 다하고 있습니다.

0개의 댓글