언어별 학습 자료/Javascript
"# JavaScript 30" 강의 - 14. JavaScript References VS Copying
CarpediemMementomori
2020. 10. 21. 13:55
학습일자
2020.10.21
학습내용
- primitive type 과 reference type 차이
: 전자는 값을 복사하지만, 후자는 참조 값을 복사해 사용하므로, 원래 인용하고 있는 변수에도 영향을 줌
Primitive Type(원시 타입) vs Reference Type (참조 타입)
자바스크립트의 뼈대가 되는 원시 타입(Primitive Type)과 참조 타입(Reference Type)에 대해 정리해보고자 한다. 원시 타입과 참조 타입 자바스크립트는 원시 타입(Primitive Type)과 참조 타입(ReferenceType)..
weicomes.tistory.com
알게된 점
- primitive type(number, string, boolean 등)은 값을 복사해서 사용하므로 원래 인용하고 있는 변수에는 영향 없으나,
reference type(object, array)는 참조 값이므로, 원래 인용하고 있는 변수에도 동일한 영향을 줌
- slice()를 사용하면, array나 object 값을 복사하 듯이 가져와 원래 변수에 영향 없이 활용 가능(slice는 시작인덱스와 끝나는 인덱스 직전의 요소를 가져와 새로운 배열로 복사)
- JSON.parse는 문자 형식의 json 파일을 object로 변환, JSON.stringify는 역으로 object 형식을 문자 형식으로 변환
// start with strings, numbers and booleans
// let age = 100;
// let age2 = age;
// console.log(age, age2);
// age = 200;
// console.log(age, age2);
// let name = 'Wes';
// let name2 = name;
// console.log(name, name2);
// name = 'wesley';
// console.log(name, name2);
// Let's say we have an array
const players = ["Wes", "Sarah", "Ryan", "Poppy"];
// and we want to make a copy of it.
const team = players;
console.log(players, team);
// You might think we can just do something like this:
// team[3] = 'Lux';
// however what happens when we update that array?
// now here is the problem!
// oh no - we have edited the original array too!
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
// So, how do we fix this? We take a copy instead!
const team2 = players.slice();
// one way
// or create a new array and concat the old one in
const team3 = [].concat(players);
// or use the new ES6 Spread => 새로운 배열을 복사하는 방법들
const team4 = [...players];
team4[3] = "heeee hawww";
console.log(team4);
const team5 = Array.from(players);
// now when we update it, the original one isn't changed
// The same thing goes for objects, let's say we have a person object
// with Objects
const person = {
name: "Wes Bos",
age: 80,
};
// and think we make a copy:
// const captain = person;
// captain.number = 99;
// how do we take a copy instead? ==> 새로운 object를 복사해서 가져오는 방법들
const cap2 = Object.assign({}, person, { number: 99, age: 12 });
console.log(cap2);
// We will hopefully soon see the object ...spread
// const cap3 = {...person};
// Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.
const wes = {
name: "Wes",
age: 100,
social: {
twitter: "@wesbos",
facebook: "wesbos.developer",
},
};
console.clear();
console.log(wes);
const dev = Object.assign({}, wes);
const dev2 = JSON.parse(JSON.stringify(wes));