Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function clone(obj) that accepts as parameter an object of reference type.
- The function should return a deep copy of the object. Write a second function compareObjects(obj,
- objCopy) that compare the two objects by reference (==) and print on the console the output given below. */
- "use strict";
- function clone(obj) {
- var deepCopyObj = new obj.constructor();
- for (var property in obj) {
- if (obj.hasOwnProperty(property)) {
- switch (typeof obj[property]) {
- case 'object':
- deepCopyObj[property] = clone(obj[property]);
- break;
- default:
- deepCopyObj[property] = obj[property];
- break;
- }
- }
- }
- return deepCopyObj;
- }
- function compareObjects(obj, objCopy) {
- return 'a == b --> ' + (obj == objCopy);
- }
- var a = {name: 'Pesho', age: 21};
- var b = clone(a);
- console.log(compareObjects(a, b));
- var a = {name: 'Pesho', age: 21};
- var b = a;
- console.log(compareObjects(a, b));
- var a = {name: 'Joro', age: 24, exams: { 'C#': 6, 'Java': 5, 'WebFunds': 6, 'JavaScript': 6, 'Python': 4}};
- var b = clone(a);
- console.log(compareObjects(a, b));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement