[ES6] Array,Object 활용

ES5에서 for문으로만 구성되었던 Array 배열의 분해라면, ES6내에서는 forEach , for ~ of 문을 제공한다.

 

Array - 반복문의 활용

 

ES5(for loop)

var arr = [1,2,3,4];
for( var i = 0 ; i<arr.length; i++){
 console.log(arr[i]);
}

ES6(forEach loop)

const arr = [1,2,3,4];

arr.forEach((item,index) => { // 1
	console.log(item,index);
});

for(let item of arr){ // 2
 console.log(item);
}

결과1
결과2

구조 분해 할당

> 배열이나 Json,Object 형태에서 속성을 해제하여서 변수로 할당하는 방식을 의미한다.

> 어떤 것을 복사한 이후에 변수로 복사해준다는 의미이다.

> 이 과정에서 분해 혹은 파괴되지 않는다는 점이 있다.

// 배열 구조 내에서 사용
const arr = [1,2,3];
const [x,y,z] = arr;

console.log(x,y,z); // 1,2,3

// 객체 구조 내에서 사용
const car = {
 type = "suv",
 color : "white",
 model : "gv80"
}

const { type, color, model } = car;
console.log(type,color,model);

// Alias 적용
const { type : type1 , color : type2, mode : type3 } = car;
console.log(type1, type2, type3 );

Spread 연산자

> 배열 혹은 객체 형태에서 기존에 있는 값을 그대로 유지해서 불러오는 방법 병합

> 구조 분해 할당 등에 다양하게 활용할 수 있다.

// 배열에서 사용하는 예시
const point = [1,2,3];
console.log(...point); // 1,2,3,

// 객체에서 사용하는 예시
const data = {
 name : "HB",
 email : "null"
}

const data2 = {
 age : 29
}

const user = {
 ...data,
 ...data2
}

 

<