[JavaScript] 배열 | 기초 개념, 반복문과 함께 응용하기, 내장 메서드

Eunji Lee·2022년 11월 5일
0

[TIL] JavaScript

목록 보기
4/22
post-thumbnail

오늘 느낀 점

  • 의사코드 작성에 신경 쓰기! → 아무리 어려운 문제도 의사코드 작성하고 차근차근 진행해보자
    • 짝꿍 없이 코드 문제 다 해결한 나 자신 너무 대견해…
  • 작성한 코드가 잘 작동할지 헷갈릴 때는 console 모드에서 직접 확인해보자 + debugger 기능 활용하기
  • 배열 인덱스를 뒤에서 세는 법도 활용하자

Chapter1. 배열(Array)

1-1. 배열의 기초 개념

  • 배열(Array) : 순서가 있는 값
    • 요소(Element) : 값
    • 인덱스(index) : 순서
      • 0부터 번호를 매김
//대괄호(Square bracket)을 활용하여 배열을 만들고, 각각의 원소는 쉼표로 구분하기
let numbers = [5, 15, 25, 30];
  • 각각의 요소는 인덱스를 활용하여 조회 및 변경할 수 있음
//배열 numbers에서 0번째 인덱스 요소 조회하기
numbers [0]; //5가 출력

//배열 numbers에서 0번째 인덱스 요소 변경하기
numbers [0] = 100;
numbers [0]; // 100이 출력
  • 2차원 배열(two dimensional array) : 배열의 요소로 1차원 배열을 가지는 배열
let numbers = [[0, 1], [2, 3], [4, 5]];
numbers [2]; //[4, 5]가 출력
numbers [1] [0]; //2가 출력
  • 속성(property) : 온점(dot)을 이용하여 변수가 가지고 있는 속성에 접근
    • .length : 배열의 길이 알아내기
      • arr.length === 0 // 빈 배열인지 확인하기 -> 조건문에 활용
      • cf) arr === [] // 참조 자료형이기 때문에 틀린 문법
let example = [0, 1, 2];
exmaple.length; // 3 출력
  • 명령(method) : 온점(dot)을 이용하여 변수가 가지고 있는 명령에 접근
    • 함수 호출하듯이 괄호를 열고 닫는 형태

1-2. 배열의 반복

  • 반복문과 배열의 조합으로 배열 응용하기
  • 예제1. 반복문을 이용해 배열의 요소 한번씩 출력하기
let numbers = [ 10, 20, 30, 40];
for(let n = 0; n < numbers.length; n++) {
	console.log(numbers [n]);
}
  • 예제2. 반복문을 이용해 배열의 모든 요소를 누적해서 더하기
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sum = 0;
for(n = 0; n < numbers.length; n++) {
	sum = sum + numbers [n];
}
console.log(sum); // 55 출력

1-3. 배열 내장 메서드

  • Array.isArray() : 타입이 배열인지 확인하기
    • cf) typeof: object 까지만 구별 → 배열인지는 구별x
let colors = ['Red', 'Green', 'Blue'];
Array.isArray(colors); //input이 배열이면 true 출력
  • Mutable Method(원본 배열을 직접 변경)
    • 배열명.push() / 배열명.pop() : 배열 맨 뒤에 새로운 요소 추가/삭제하기
      • .push(): 변경된 배열의 길이 리턴
      • .pop(): 제거된 요소 리턴
    • 배열명.unshift() / 배열명.shift() : 배열 맨 앞에 새로운 요소 추가/삭제하기
      • .unshift() : 변경된 배열의 길이 리턴
      • .shift() : 제거된 요소 리턴
    • 배열명.splice(start, deleteCount, addElement) : 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하기
//배열 맨 뒤에 새로운 요소 추가하기
let names = ['James', 'Steve', 'Andrew'];
console.log(names.push('Daniel')); //변경된 배열의 길이인 4 출력
console.log(names); //['James', 'Steve', 'Andrew', 'Daniel'] 출력
//배열 맨 뒤에 요소 삭제하기
console.(names.pop()); //'Daniel' 출력
console.log(names); //['James', 'Steve', 'Andrew'] 출력
//배열 맨 앞에 새로운 요소 추가하기
let countries = ['USA', 'Canada', 'UK', 'France'];
console.log(countries.unshift('Korea')); // 변경된 배열의 길이인 5가 출력
console.log(countries); // ['Korea', 'USA', 'Canada', 'UK', 'France']가 출력됨
//배열 맨 앞에 요소 삭제하기
console.log(countries.shift()); // 'Korea' 출력
console.log(countries); //['USA', 'Canada', 'UK', 'France']가 출력됨
//배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하기
let alphabet = ['A', 'B', 'C', 'D', 'E'];
console.log(alphabet.splice(3, 2, 'F')); //삭제할 요소인 ['D', 'F'] 가 출력
console.log(alphabet); //['A', 'B', 'C', 'F']가 출력
  • Immutable Method(원본 배열을 변경하지 않음)
    • 배열명.slice(start, end) → 일종의 복붙하기
      • 인덱스 start부터 인덱스 [end-1]까지 잘라짐
      • immutable method이므로 새로운 변수에 할당해서 사용하기!
    • 배열명.concat(요소 또는 배열) : 추가하기
//.slice
let month = ['Jan', 'Feb', 'March', 'April', 'May'];
console.log(month.slice(0, 3)); //['Jan', 'Feb', 'March']
console.log(month); //['Jan', 'Feb', 'March', 'April', 'May']
//.concat
let num1 = [0, 1, 2];
let num2 = [3, 4, 5];
console.log(num1.concat(num2)); //[0, 1, 2, 3, 4, 5] 출력
console.log(num2.concat(num1)); //[3, 4, 5, 0, 1, 2] 출력
  • 배열명.indexOf(searchElement) : 배열에 searchElement가 있으면 해당 요소의 인덱스 출력 → 없으면 -1 출력
let beverage = ['water', 'juice', 'coffee', 'tea'];
beverage.indexOf('water'); // 0 출력
beverage.indexOf('milk'); // -1 출력
//응용하기: 배열에 특정 요소가 있는지 확인하기
function hasElement(arr, element) {
	return arr.indexOf(element) !== -1;
}
hasElement(beverage, 'milk'); // False 출력
  • 배열명.includes(searchElement) : 배열에 searchElement가 있으면 True 출력
    • Internet Explore 에서 작동x → 호환성이 떨어짐
beverage.includes('water'); //true 출력

0개의 댓글