JS 객체는 Rust의 struct와 HashMap을 반반 섞은 느낌이다 — 필드는 정해져 있지 않아도 되고, 대괄호로 동적 키 접근도 된다.
const reading = {
time: "11:00",
tempC: 81.2,
voltage: 4.98,
throttled: true,
};
reading.tempC // 81.2 — 점 표기, 키를 알 때
reading["tempC"] // 81.2 — 대괄호, 키가 변수/동적일 때
const key = "tempC";
reading[key] // 81.2
reading.humidity // undefined — 없는 키는 에러 안 나고 undefined
const { time, tempC } = reading; // reading.time, reading.tempC를 바로 변수로
const { tempC: temperature } = reading; // 이름 바꿔서 받기
const { humidity = 0 } = reading; // 없으면 기본값
// 함수 파라미터에서 바로 구조분해 — 실무에서 제일 많이 씀
function describe({ time, tempC }) {
return `${time} — ${tempC}°C`;
}
describe(reading);
const copy = { ...reading }; // 얕은 복사
const updated = { ...reading, tempC: 70.0 }; // 필드 하나만 덮어쓴 새 객체 (원본 불변 유지)
const merged = { ...defaults, ...userConfig }; // 뒤에 오는 쪽이 우선
{ ...a }는 a의 1단계 프로퍼티만 복사한다.
const city = response?.location?.city ?? "알 수 없음";
// response가 null이거나 location이 없어도 에러 안 나고 "알 수 없음"으로 떨어짐
sensor?.calibrate?.(); // calibrate 메서드가 있을 때만 호출
_submissions/day06.js과제 1. SensorReading 만들기
{ time, tempC, voltage, throttled } 형태의 객체를 리턴하는 팩토리 함수를 작성한다.
function makeReading(time, tempC, voltage, throttled = false) {
// TODO
}
// makeReading("14:00", 63.5, 5.01) → { time: "14:00", tempC: 63.5, voltage: 5.01, throttled: false }
과제 2. 구조분해 파라미터
formatReading(reading)을 함수 파라미터 자리에서 구조분해로 받아 작성한다: "[14:00] 63.5°C (5.01V)" 형식 문자열을 리턴.
과제 3. 불변 업데이트
withThrottled(reading): 원본은 건드리지 않고, throttled만 true로 바뀐 새 객체를 리턴한다 (spread 사용).
과제 4 (도전). 안전한 중첩 접근
getNestedTemp(data): data.sensor.reading.tempC 형태로 깊이 중첩된 값을 가져오되, 중간 어디가 없어도(data.sensor가 없다든지) 에러 없이 null을 리턴하도록 옵셔널 체이닝으로 작성한다.
// getNestedTemp({ sensor: { reading: { tempC: 70 } } }) → 70
// getNestedTemp({}) → null
cd ~/Documents/javascript-2주완성
bun _grade.ts day06