리액트/ES6

객체 전개 연산자 / 가변, 불변변수

dev.tkim42 2021. 7. 30. 16:22
//객체 전개 연산자

// ES5 예제
var objectOne = { one: 1, two: 2, other: 0 };
var objectTwo = { three: 3, four: 4, other: -1 };

var combined = {
  one: objectOne.one,
  two: objectOne.two,
  three: objectTwo.three,
  four: objectTwo.four,
};
//객체 내장함수 assing() 첫 번째 인자는 결과로 반환할 객체({}) , 나머지 인자는 병합할 객체이다.
//이때 병합할 객체는 앞에 있는 객체부터 덮어 쓴다. objectTwo의 값으로 덮어 쓴다.
var combined = Object.assign({}, objectOne, objectTwo);
// combined = { one: 1, two: 2, three: 3, four: 4, other: -1}
var combined = Object.assign({}, objectOne, objectTwo);
//중복되는 키값이 있으면 이후에 전달된 객체(objectOne)의 값으로 덮어쓴다.
// combined = { one: 1, two: 2, three: 3, four: 4, other: 0}
var others = Object.assign({}, combined);
delete others.other;

// ES6 예제
var combined = {
  ...objectOne, //두 객체를 병합할 때 중복된 키값들은 마지막에 사용한 객체의 값으로 덮어쓴다
  ...objectTwo,
};
// combined = { one: 1, two: 2, three: 3, four: 4, other: -1}
var combined = {
  ...objectTwo,
  ...objectOne,
};
// combined = { one: 1, two: 2, three: 3, four: 4, other: 0}
var { other, ...others } = combined;
//객체에서 특정값을 추출할 때는 추출하려는 키 이름(other)을 맞추고 나머지는 전개 연산자로 선언된 변수(others)에 할당할 수 있다.
// others = { one: 1, two: 2, three: 3, four: 4}

 

//가변 변수 , 불변 변수

const num = 1;
num = 3; // 타입 에러가 발생합니다

const str = "문자";
str = "새 문자"; // 타입 에러가 발생합니다

const arr = [];
arr = [1, 2, 3]; // 타입 에러가 발생합니다

const obj = {};
obj = { name: "내 이름" }; // 타입 에러가 발생합니다

const arr2 = [];
arr2.push(1); // arr2 = [1]
arr2.splice(0, 0, 0); // arr2 = [0,1]
arr2.pop(); // arr2 = [1]

const obj2 = {};
obj2["name"] = "내이름"; // obj2 = { name: '내이름' }
Object.assign(obj2, { name: "새이름" }); //obj2 = { name: '새이름' }
delete obj2.name; //obj2 = {}

const num1 = 1;
const num2 = num1 * 3; // num2 = 3

const str1 = "문자";
const str2 = str1 + "추가"; // str2 = '문자추가'

const arr3 = [];
const arr4 = arr3.concat(1); // arr4 = [1]
const arr5 = [...arr4, 2, 3]; // arr5 = [1, 2, 3]
const arr6 = arr5.slice(0, 1); // arr6 = [1], arr5 = [1, 2, 3]
const [first, ...arr7] = arr5; // arr7 = [2, 3], first = 1

const obj3 = { name: "내이름", age: 20 };
const obj4 = { ...obj3, name: "새이름" }; // obj4 = { name: '새이름', age: 20}
const { name, ...obj5 } = obj4; // obj5 = { age: 20 }

const arr = [1, 2, 3];
// 가변 변수를 사용한 예
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
// iterator 방식의 for-in 루프와 함께 불변 변수를 사용한 예
for (const item in arr) {
  console.log(item);
}

// forEach 함수를 활용한 예
arr.forEach((item, index) => {
  console.log(item);
  console.log(index);
});