{name:'Code Kim',isDeveloper: true}
데이터를 묶음으로 관리함
<객체(object)의 기본적인 형태>
let mySelf = { name:'Code Kim', location:{ country:'South Korea', --->객체도 중첩이 가능함 city:'Seoul'}, age: 30, cats:['냥순','냥돌;] }
mySelf의 property는 4개(name,location,age,cats)
property는 2가지로 나뉨
- Key : name,location,age,cats
- Value : Code Kim, country,city,30,...
ex)mySelf의 name이라는 key는 code kim이라는 value를 가진다.
예시1.
let myself={ name:'Code Kim', location:{ country:'South Korea', city:'Seoul'}, age:30, cats:['냥순','냥돌'] } console.log(myself) // [object Object] { age: 30, cats: ["냥순", "냥돌"], location: [object Object] { city: "Seoul", country: "South Korea" }, name: "Code Kim" } //순서대로 출력되지 않는게 정상.
let myObject = {
key:value}
(1). Dot Notation
let myself={ name:'Code Kim', country:'South Korea', age:30, cats:['냥순','냥돌'] } console.log(myself.name) console.log(myself.age) //Code Kim과 30 출력됨
(2)Braket Notation
let myself={ name:'Code Kim', country:'South Korea', age:30, cats:['냥순','냥돌'] } console.log(myself['name']) console.log(myself['age'])-->대괄호 안에 따옴표 필쑤!
예시로 알아보기
let myself = { name: 'Code Kim', country: 'South Korea', age: 30, cats: ['냥순','냥돌'] } let myCats = myself['cats']-->myCats라는 변수 선언 console.log(myCats) // ['냥순','냥돌']
Key자리에는 변수가 올 수 없다.
자바스크립트의 Key는 기본적으로 string이다
근데 자바스크립트가 따옴표가 없이도 사용할 수 있게끔 한것. 그래서 string을 변수에 담아도 사용할 수 있음.
let myself={ name:'Code Kim', country:'South Korea', age:30, cats:['냥순','냥돌'] } let myKey = 'cats'-->냥순 냥돌부분 cats를 mykey라는 변수로 선언 console.log(myself['cats']) console.log(myself[myKey]) //["냥순", "냥돌"] ["냥순", "냥돌"]
(!)그러나 Dot notation 에서는 사용할 수 없다
위 예시에 추가해서 확인해보자
let myself={ name:'Code Kim', country:'South Korea', age:30, cats:['냥순','냥돌'] } let myKey = 'cats'-->변수부분 console.log(myself['cats']) console.log(myself[myKey]) console.log(myself.myKey)-->추가 //["냥순", "냥돌"] ["냥순", "냥돌"] undefined------>언디파인드 나옴.
let myself={ name:'Code Kim', country:'South Korea', age:30, cats:['냥순','냥돌'], myKey:'Hello world!'--->추가함 } let myKey = 'cats' console.log(myself['cats']) console.log(myself[myKey]) console.log(myself.myKey) //["냥순", "냥돌"] ["냥순", "냥돌"] "Hello world!"
왜냐하면 myKey라는 단어가 Key로도 존재하고 변수로도 존재하는 상황. 콘솔부분의 myKey는 변수로 인식해서 cats의 밸류를 출력한다.
닷노테이션은 변수를 사용할 수 없어서 객체안의 Key로 인식함.