#8 객체
- key
: 문자열로 작성
: 중복되어도 문제는 없지만 추천하지 않는다.
- property (객체 프로퍼티)
: 속성, 객체가 갖는 데이터
: 여러 개의 값을 가질 수 있다.
: 어떤 자료형이든 사용 가능
let person = new Object(); //생성자 이용
let person = {
key: "value", //프로퍼티
key1: 123,
key2: true,
key3: undefined,
key4: [1, 2],
key5: function() {}
}; //객체 리터럴 방식
console.log(person); //{key: "value", key1: "value2"}
console.log(person.key1); //123 (점표기법)
console.log(person.key6); //undefined
//괄호 표기법
myKey = "key1";
console.log(person["key1"]); //123
console.log(person[myKey]); //123
*점 표기법 vs 괄호 표기법
: 괄호 표기법에서는 변수를 식별자로 사용할 수 있지만, 점 표기법에서는 사용할 수 없다.
< 프로퍼티 추가, 수정, 삭제 >
const person = {
name: "이정환",
age: 25
};
//프로퍼티 추가
person.location = "한국";
person["gender"] = "남성";
//프로퍼티 수정
person.name = "김철수";
person["age"] = 40;
//상수 훼손이므로 오류 발생
person = {
age = 20
};
//프로퍼티 삭제
delete person.age;
delete person["name"];
person.name = null; //추천
< 함수 호출 >
const person = {
name: "이정환", //멤버
age: 25, //멤버
say: function () {
console.log("안녕");
} //메서드
};
person.say(); //안녕
person["say"](); //안녕
const people = {
name: "이정환",
age: 25,
say: function () {
console.log(`안녕 나는 ${this.name}`); //${person.name}
}
};
people.say() //안녕 나는 이정환
console.log(`name: ${"name" in people}`); //true 객체 안에 해당 프로퍼티가 있는 지 확인
#9 배열
: 비원시 자료형
: 순서 있는 요소들의 집합
let arr = [1, "2", true, null, undefined, {}, [], function() {}]; //배열 리터럴
console.log(arr); //[1, "2", true, null, undefined, Object, Array(0), f()]
console.log(arr[0]); //1
let array = [1, 2, 3, 4, 5];
arr.push(6);
arr.push({ key: "value"});
console.log(array); //[1, 2, 3, 4, 5, 6, Object]
console.log(array.length); //7
#10 반복문
for (초기식; 조건식; 연산) {
반복 수행할 명령
}
for (let i = 1; i <= 100; i++) {
console.log("김철수");
}
//배열 순회
const arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//객체 순회
let person = {
name: "이정환",
age: 25,
tall: 175
};
const personKeys = Object.keys(person) //["name", "age", "tall"]
for (let i = 0; i < personKeys.length; i++) {
const curKey = personKeys[i];
const curValue = person[curKey];
console.log(`${curKey} : ${curValue}`);
}
이정환님의 인프런 강의 "한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지"를 참고하여 작성하였습니다.
'Web > JavaScript' 카테고리의 다른 글
JavaScript 응용 #1 Truthy & Falsy, 삼항 연산자, 단락회로 평가 (0) | 2023.09.14 |
---|---|
JavaScript 기본 #4 배열 내장 함수 (0) | 2023.09.10 |
JavaScript 기본 #2 함수 (0) | 2023.09.07 |
JavaScript 기본 #1 변수, 상수, 자료형, 연산자, 조건문 (0) | 2023.09.07 |
자바스크립트 DOM & EVENT #2 부모, 자식, 형제 노드 (0) | 2023.08.27 |