TIL - #5 배열, 반복문

MIN KYOUNG KIM·2022년 1월 24일
0

Array

배열이란? 관련 있는 데이터를 하나의 변수에 할당 여 관리하기 위해 사용되는 데이터 타입

Array가 필요한 이유

배열이 필요한

  • 단일 데이터(Single data)가 아닌 다수의 데이터(Multiple data) 저장
  • 연관있는 데이터를 함께 변수에 저장하므로 데이터를 찾는데 용이

Array 선언

let name = ['Jane','Mike','David','Alice'];

//[]안에 들어간 데이터는 element라고 부른다.

Array의 값을 추가,삭제하는 방법

  • push()
  • unshift()
  • pop()
  • shift()

push()

  • push(): add items to the end of an array
let students = ['June','Willy','Anne'];
console.log(students); // ["June", "Willy", "Anne"]
students.push('George');
console.log(students); //["June", "Willy", "Anne", "George"]

unshift()

  • unshift(): Add items to the beginning of an array
let students = ['June','Willy','Anne'];
console.log(students); //["June", "Willy", "Anne"]
students.unshift('George');
console.log(students);["George", "June", "Willy", "Anne"]

pop()

  • pop(): Remove an item from the end of an array
let students = ['June','Willy','Anne'];
console.log(students); //['June','Willy','Anne']
students.pop();
console.log(students); ['June','Willy']

shift()

  • shift() : Add items to the beginning of an array
let students = ['June','Willy','Anne'];
console.log(students); //["June", "Willy", "Anne"]
students.shift();
console.log(students); //["Willy", "Anne"]

반복문이 필요한 이유와 사용하는 방법

  • 반복되는 작업을 수행하기 위해 필요

for

for(초기문; 조건문; 증감식){

//반복할 코드 작성하는 부분 

}
let result = 0;

for(let i = 0; i < 10 ; i++){
		result += i;

}

console.log(result);

초기화문

  • 초기화문 작성 시 변수 선언자를 써주어야 합니다.
  • 변수명은 보통 index를 의미하는 i로 선언합니다.
  • index가 증가할 경우 숫자는 보통 0부터 시작합니다.

조건문

  • index의 범위를 설정합니다.
  • index가 증가할 경우 특정한 숫자 미만 혹은 이하로 설정합니다.
  • index가 감소할 경우 0 이상으로 설정합니다.
  • 조건문이 true일 경우 반복문을 계속 실행합니다.
  • 조건문이 false일 경우 반복문이 종료됩니다.

증감식

  • index가 1씩 증가할 경우 ++을 써줍니다.(index의 숫자가 하나씩 증가)
  • index가 1씩 감소할 경우 --를 써줍니다.(index의 숫자가 하나씩 감소)
  • i++은 i = i+1 을 줄여서 쓴 것입니다. i += 1 로 표현할 수도 있습니다.
  • i++는 ++1로 표현할 수 있습니다.

배열과 반복문을 함께 자주 사용하는 이유

반복문은 동일한 명령을 정해진 횟수만큼 반복하여 수행하도록 제어하는 명령문으로 구문(syntax)에는 주로 변수 증감을 위한 명령을 많이 사용하는데, 배열의 index가 해당 역할을 수행하기에 적합하기 때문에 배열과 반복문은 자주 함께 쓰인다.

배열의 메서드 5가지와 사용 방법

Array - JavaScript | MDN

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다

  • slice 메서드는 배열 내의 특정한 요소의 index 범위에 따라 새로운 배열을 리턴합니다.
  • splice 메서드와는 다르게 slice 메서드는 원본 배열을 변형시키지 않습니다.
  • 그렇기 때문에 이 메서드를 사용할 때는 slice 메서드를 적용한 새로운 변수를 선언해주어야 합니다.
const findFruits = () => {
  let foodBox = ['🍕', '🍤','🍇' ,'🥝','🍒','🍉','🍗', '🍟' ];

  let new_foodBox = foodBox.slice(2,6);
  console.log(new_foodBox);

  return new_foodBox
  
}

findFruits();

filter() 메서드는 array 관련 메서드로 조건에 맞는 요소들만 모아서 새로운 배열을 반환합니다.

let numbers = [10, 4, 32, 17, 5, 2]

let result = numbers.filter((value) => value > 10);
console.log(result); // [32,17]
profile
sin prisa pero sin pausa

0개의 댓글