Today I Learned/JavaScript

[JavaScript] 배열과 객체

BaGyun 2022. 2. 11. 21:01

배열의 선언방법

let arr = []; // 빈배열 선언
arr = [1, 2, 3, 4, 5]; // 배열에 값 할당
console.log(arr) // [1,2,3,4,5]

 

대괄호([])를 이용해서 배열을 만듭니다.
배열은 순서가 있는 값으로, 각 요소의 순서를 인덱스라고 부르며, 1이 아닌 0부터 번호를 매깁니다.
각각의 값들을 요소(element)라고 부르며, 쉼표(comma)로 구분해줍니다.

객체의 선언방법

let user = {};
user = {
  name = "Bagyun",
  email = "Bagyun@naver.com",
  city = "Seoul"
}

 

객체는 중괄호({})를 이용해서 만듭니다.
객체는 키와 값(key-value)로 값을 넣어야합니다.
각각의 값들을 속성(Property)라고 부르며, 한 쌍마다 쉼표(comma)로 구분해줍니다.

 

배열의 값에 접근하기

let myNumber = [73 ,98 ,86 ,61 ,96];
console.log(myNumber[0]) //73
console.log(myNumber[2]) //86
console.log(myNumber[3]) //61
myNumber[3] = 200
console.log(myNumber[3]) //200

 

객체의 값 접근하기

let user = {};
user = {
  name : "Bagyun"
  email : "Bagyun@naver.com"
  city : "Seoul"
}

/*Dot notation*/
console.log(user.name) // "Bagyun"
console.log(user.city) // "Seoul"

/*Breacket notation*/
console.log(user['name']) // "Bagyun"
console.log(user['city']) // "Seoul"

/*값 변경*/
user.city = "Busan"
console.log(user.city) // "Busan

 

값의 추가,삭제 그리고 각종 메소드

let arr = [1, 2, 3, 4]

arr.push(100) // [1, 2, 3, 4, 100] 마지막 index에 추가

arr.pop() // [1, 2, 3, 4] 마지막 index 삭제

arr.unshift(100) // [100, 1, 2, 3, 4] 첫번째 index에 추가

arr.shift() // [1, 2, 3, 4] 첫번째 index 삭제

let newArr = arr.concat(50)
console.log(arr) // [1, 2, 3, 4]
console.log(newArr) // [1, 2, 3, 4, 50]

 

push,pop,unshift,shift 와 concat의 차이
-불변성(Immutable)의 차이인데 concat은 원본을 바꾸지 않으며, 새로 만든 배열을 반환합니다.

 

객체의 값 추가, 삭제, 키 확인법

let user = {};
user = {
  name : "Bagyun",
  email : "Bagyun@naver.com",
  city : "Seoul"
}

/* 값 추가하기 */
user.sex = "male"
user['age'] = 5

/*
user = {
  name : "Bagyun",
  email : "Bagyun@naver.com",
  city : "Seoul",
  sex : "male",
  age : 5
}
*/

delete user.sex // 값 삭제하기

/*
user = {
  name : "Bagyun",
  email : "Bagyun@naver.com",
  city : "Seoul",
  age : 5
}
*/

/* 키 확인하기 */
"name" in user // true
"sex" in user // false