코딩/코드스테이츠 45기(FE)

블로깅 챌린지 3주차 - [JS] 배열, 객체

2워노 2023. 4. 25. 17:07

1. 배열

⚡️ 배열 기초

  • 배열은 같은 자료들을 담는 자료 구조중의 하나이다.
  • 배열의 선언
// 배열 Declaration //
const arr1 = [a, b, c, d];
const arr2 = New Array[a, b, c, d];

 

  • 배열의 인덱스와 길이
const fruits = ['apple', 'orange', 'grape'];
console.log(fruits);
console.log(fruits.length); // 3
console.log(fruits[0]); // apple
console.log(fruits[2]); // grape
console.log(fruits[3]); // undefined
console.log(fruits[fruits.length - 1]); // grape

 

  • 배열의 반복문(Looping ove an Array)
const fruits = ['apple', 'oragne', 'grape', 'melon'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// apple, oragne, grape, melon 순서대로 출력
// for of 문법 사용
for (let fruit of fruits) {
  console.log(fruit);
}

//결과는 위와 동일

 

 

⚡️ 배열의 메서드

  • push : 배열의 가장 마지막에서 부터 값을 추가한다.
const fruits = ['apple', 'oragne', 'grape', 'melon']; 

fruits.push('pear', 'onion');

console.log(fruits);
// ['apple', 'oragne', 'grape', 'melon', 'pear', 'onion']

 

  • pop: 배열의 가장 마지막 값을 삭제한다.
console.log(fruits);
// ['apple', 'oragne', 'grape', 'melon', 'pear', 'onion']

fruits.pop();
console.log(fruits);
// ['apple', 'banana', 'kiwi', 'melon', 'pear']

 

  • unshift: 배열의 가장 앞에서부터 값을 추가한다.
fruits.unshift('berry');
console.log(fruits);
// ['berry', 'apple', 'orage', 'grape', 'melon', 'pear']

 

  • shift: 배열의 가장 앞에있는 값을 삭제한다.
fruits.shift();
console.log(fruits);
// ['apple', 'orage', 'grape', 'melon', 'pear']
더보기

shift와 unshift 메서드는 느리게 동작한다.

앞에서부터 값을 넣거나 삭제하기 위해선 뒤에있던 요소들이 전부 이동해야 하기 때문이다.

 

 

  • splice: 배열에서 원하는 인덱스의 값을 삭제하거나 추가할 수 있다.
const fruits = ['apple', 'oragne', 'grape', 'melon']; 

fruits.splice(1, 1); // 인덱스 1부터 1개 삭제
console.log(fruits);
// ['grape', 'grape', 'melon', 'pear']

fruits.splice(2); // 인덱스 2부터 뒤로 전부 다 삭제
console.log(fruits);
// ['apple', 'oragne']


fruits.splice(3, 1, 'kiwi', 'berry'); // 1인덱스부터 1개 삭제하고 그 자리에 'grape', 'berry' 추가
console.log(fruits);
// ['apple', 'oragne', 'grape','kiwi', 'berry' ]

 

  • 배열 검색 메서드 : indexOf, lastIndexOf, includes
const fruits = ['apple', 'oragne', 'grape', 'melon']; 

//* indexOf 메서드 *//

console.log(fruts.indexOf('apple')) // 0

console.log(fruts.indexOf('onion')); // 없는 값을 입력하면 -1이 반환된다.



//* lastIndexOf 메서드 *//

console.log(fruts.lastIndexOf('apple')); // 3



//* includes 메서드 *//

console.log(fruts.include('orage')); //  아이템이 배열내 포암되어 있으면 true 반환

console.log(fruts.include('onion')); // 아이템이 배열내 포암되어 있지 않으면 false 반환

 

 

2. 객체

⚡️ 객체란?

  • 자바스크립트는 객체 기반 프로그래밍 언어로, 자바스크립트는 구성하는 거의 '모든것'이 객체라고 할 수있다.
  • 원시형 값을 제외한 나머지 값( 함수, 배열 등) 은 모두 객체로 분류된다.
  • 원시형은 하나의 값만 나타내지만 객체형(참조형)은 다양한 값(원시값 혹은 다른 객체)을 하나의 단위로 구성한 복합적인 자료 구조라고 할 수 있다.
  • 또한, 원시형의 값은 변경 불가능한 값(ummutable value)이지만, 객체는 변경 가능한 값(mutable value) 이다.

 

❗️ 객체의 종류

  • 배열
  • 함수
  • 객체
  • 날짜
  • 수학
  • 정규표현식
  • Boolean도 객체가 될 수 있다. (new 키워드로 정의된 경우)
  • 숫자도 객체가 될 수 있다. (new 키워드로 정의된 경우)
  • 문자열도 객체가 될 수 있다. (new 키워드로 정의된 경우)

 

❗️ 객체의 구성

const person = {
  name: 'WONHO',
  age: 30
};

// 속성(property): name, age
// 값(value): 'WONHO', 30
  • 객체는 0개 이상의 요소(property)로 구성된 집합이다.
  • 요소(property)는 키(key)와 값(value)으로 구성되어 있다.
  • 자바스크립트에서 사용할 수 있는 모든 값은 속성 값이 될 수 있다.

 

❗️ 객체의 속성(property)과 메서드

  • 객체 내부에 있는 값을 속성(property)라고 하며, 객체의 속성은 모든 자료형이 될 수 있다.
  • 객체의 속성 중 자료형이 함수인 경우에 이 속성을 특별히 메서드(method)라고 부른다.
    <script>
        var person = {
            //property
            name : 'WONHO',
            years : 30,
            married : false,
 
            //method
            eat : function(food) {
                console.log(this.name + ' eats ' + food); //this키워드 사용
            }
        };
 
        person.eat('banana');
    </script>

// 'WONHO eats banana' 출력
this 키워드
  • 객체내의 메서드에서 객체가 가진 속성을 사용할때에는 반드시 this 키워드를 사용하여야 한다. (생략 불가능)

 

❗️ 배열과 객체 구조의 차이

  • 배열은 순서를 가지며, 객체는 의미를 가진다.

 

 

⚡️ 객체 기초

❗️ 객체 생성 방법

  • 객체 리터럴을 사용하여 단일 객체를 정의
// 객체 리터럴: 중괄호 안에 key: value 목록
var person = {
	firstName:"WONHO",
	lastName:"LEE",
	age:30,
	eyeColor:"brown"
};

 

  • new 키워드를 사용하여 단일 객체를 정의
var person = new Object();
person.firstName = "WONHO";
person.lastName = "LEE";
person.age = 30;
person.eyeColor = "brown";
가독성, 단순성과 실행 속도를 위해서라면 객체 리터럴 방법을 사용하는것이 권장된다.

 

❗️ 객체 접근 방법

let person = {
  name: "WONHO",
  age: 30,
  address: "서울특별시 은평구"
};

//*  방법 1 *//
let myName = person.name; // 'WONHO'
let myAge = person.age; // 30


//*  방법 2 *//
let myName2 = person['name'];  // 'WONHO'
let myAge2 = person['age']; // 30

 

❗️ 객체에 Key / Value 추가 방법

let person = {
  name: "WONHO",
};


let myName = person.name; // 'WONHO'
let myAge = person.age; // undefined (존재하지 않는 key / value)

// 추가 방법
person.age = 30; 혹은 person["age"] = 30;

console.log(person.age); // 결과 : 30

 

❗️ 객체에 Key / Value 수정 방법

let person = {
  name: "WONHO",
  age: 30,
};

// 수정 방법

person.age = 20; 혹은 person["age"] = 20;

console.log(person.age); // 결과 : 20

 

❗️ 객체에 Key / Value 삭제 방법

let person = {
  name: "WONHO",
  age: 30,
};

// 삭제 방법

delete person.age

console.log(person.age); // undefined

 

 

Reference

 - MDN JavaScript 객체 기본