06-3 객체와 배열 고급
1. 속성 존재 여부 확인
const wishlist={
name: 'macbook'
price: 1500000
}
// 방법 1
if (wishlist.name !== undefined){
console.log('name 속성이 있습니다')
} else{
console.log('name 속성이 없습니다')
//방법 2
if (wishlist.name){
console.log('name 속성이 있습니다')
} else{
console.log('name 속성이 없습니다')
//방법3
object.name || console.log('name 속성이 있습니다')
ㄴ 빈 문자열은 false로 취급되므로 방법 2와 방법 3에서는 빈 문자열이 아니라는 가정하에 사용하는 것이 안전하다.
2. 배열 기반의 다중 할당
다중 할당을 사용하면 여러 개의 변수에 한 번에 값을 할당할 수 있다.
> let [a,b] = [1,2]
undefined
> console.log(a,b)
1,2
> let array=[1,2,3,4,5]
undefined
> const [c,d,e] = array
undefined
> console.log(c,d,e)
1 2 3
3. 객체 기반의 다중 할당
객체 내부에 있는 속성을 꺼내서 변수로 할당할 때 객체 기반의 다중 할당을 사용할 수 있다.
const wishlist={
name : 'macbook',
price : 1500000
}
const {name, price} = wishlist
const {a=name, b=price} = wishlist
console.log(name,price)
console.log(a,b)
<실행결과>
'macbook', 1500000
'macbook', 1500000
4. 배열 전개 연산자
1) 얕은 복사
let arr1 = [1,2]
let arr2 = arr1
arr2.push(3)
arr2.push(4)
console.log(arr1)
console.log(arr2)
<실행결과>
(4) [1,2,3,4]
(4) [1,2,3,4]
ㄴ arr2에 arr1을 복사하고 arr2에만 push를 했는데 출력 결과를 보니 arr1에도 변화가 나타났다. 이것이 얕은 복사인데
arr2=arr1과 같이 복사를 하게 되면 배열에 다른 이름을 붙이는 효과일 뿐이다.
2) 깊은 복사
let arr1 = [1,2]
let arr2 = [...arr1]
arr2.push(3)
arr2.push(4)
console.log(arr1)
console.log(arr2)
<실행결과>
(4) [1,2]
(4) [1,2,3,4]
ㄴ arr2=[... arr1]처럼 전개 연산자를 사용하여 깊은 복사를 하면 두 배열이 완전히 독립적으로 작동한다.
let arr1=[1,2]
let arr2 = [3,...arr1,4]
let arr3 = [...arr1,...arr2]
console.log(arr1)
console.log(arr2)
console.log(arr3)
<실행결과>
(2) [1,2]
(4) [3,1,2,4]
(6) [1,2,3,1,2,4]
5. 객체 전개 연산자
const wishlist1={
name : 'macbook',
price : 1500000
}
const wishlist2=wishlist1
wishlist2.name = 'imac'
wishlist2.price = 2000000
console.log(JSON.stringify(wishlist1))
console.log(JSON.stringify(wishlist2))
<실행결과>
{"name":"imac","price":2000000}
{"name":"imac","price":2000000}
ㄴ 배열과 마찬가지로 wishlist 2 = wishlist1 처럼 객체를 복사하면 얕은 복사가 되어 독립적으로 작용이 되지 않는다.
const wishlist1={
name : 'macbook',
price : 1500000
}
const wishlist2={...wishlist1}
wishlist2.name = 'imac'
wishlist2.price = 2000000
console.log(JSON.stringify(wishlist1))
console.log(JSON.stringify(wishlist2))
<실행결과>
{"name":"macbook","price":1500000}
{"name":"imac","price":2000000}
ㄴ wishlist2={...wishlist1} 로 복사하면 깊은 복사가 되어 두 객체가 독립적으로 작용한다.
const wishlist1={
name : 'macbook',
price : 1500000,
color : 'space gray'
}
const wishlist2 = {
...wishlist1
name : 'imac',
price : 2000000,
secondhand : false
}
console.log(JSON.stringify(wishlist1))
console.log(JSON.stringify(wishlist2)
<실행결과>
{"name:"macbook","price":1500000,"color":"spacegray"}
{"name":"imac","price":2000000,"color":"spacegray","secondhand":false}
'혼공스보면서 혼공스(JS)' 카테고리의 다른 글
| CH7. 문서 객체 모델- 이벤트 활용 (0) | 2021.07.13 |
|---|---|
| CH7. 문서 객체 모델- 문서 객체 조작하기 (0) | 2021.07.12 |
| CH6. 객체- 객체의 속성과 메소드 사용하기 (0) | 2021.07.11 |
| CH6. 객체- 객체의 기본 (0) | 2021.07.10 |
| CH5. 함수- 함수 고급 (0) | 2021.07.09 |