다음 예제의 Apple
이나 Banana
같은 데이터를 배열의 아이템(item) 혹은 요소(Element)라고 부른다.
let fruits
// 생성자
fruits = new Array('Apple', 'Banana', 'Cherry')
// 리터럴
fruits = ['Apple', 'Banana', 'Cherry']
// 배열의 아이템 인덱싱
console.log(fruits[1]) // 'Banana'
// 배열의 길이
console.log(fruits.length) // 3
// 첫 번째 아이템 인덱싱
console.log(fruits[0]) // 'Apple'
// 마지막 아이템 인덱싱
console.log(fruits[fruits.length - 1]) // 'Cherry'
// 마지막 아이템 인덱싱 오류
console.log(fruits[-1]) // undefined
key:value(속성:값) 형태로 더 복잡한 데이터 구조를 나타낼 때 사용합니다.
let user
// 생성자1
user = new Object()
user.name = 'wooseongjeon'
user.age = 28
// 생성자2
function User() {
this.name = 'wooseongjeon'
this.age = 28
}
user = new User()
// 리터럴
user = {
name: 'wooseongjeon',
age: 28
}
console.log(user.name) // 'wooseongjeon'
console.log(user.age) // 28
점 표기법과 대괄호 표기법
객체의 멤버(속성과 메소드)를 점 표기법(Dot notation)과 대괄호 표기법(Bracket notation)
두가지로 표현 할 수 있다.
const user = {
name: 'wooseongjeon',
age: 28
}
// 점 표기법
console.log(user.name) // 'wooseongjeon'
console.log(user.age) // 28
// 대괄호 표기법
console.log(user['name']) // 'wooseongjeon'
console.log(user['age']) // 28
점 표기법과 대괄호 표기법은 체이닝으로 작성 할 수 있습니다.
const userA = {
name: 'wooseongjeon',
age: 28
}
const userB = {
name: 'cherry',
age: 8,
parent: userA
}
console.log(userB.parent.name) // 점 표기법 // wooseongjeon // userB의 부모의 이름
console.log(userB['parent']['name']) // 대괄호 표기법 // wooseongjeon // userB의 부모의 이름
속성 삭제 (delete)
const user = {
name: 'wooseongjeon',
age: 28
}
delete user.age
console.log(user) // { name: 'wooseongjeon' }
자바스크립트에서 함수(function)는 1급 객체(First-class object)로,
하나의 값으로 변수나 인수 혹은 반환이 가능하다.
function x() {
return 123
}
console.log(typeof x) // function // x 자체의 타입
console.log(typeof x()) // number // x가 작동된 결과값의 타입
console.log(x) // f x() { return 123 } // x자체
console.log(x()) // 123 // x작동 결과값
const a = function () {
console.log('Hi!')
}
const b = function (c) {
console.log(c)
c()
}
b(a)
ƒ () {
console.log('Aa!')
}
Aa!