Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6、深浅拷贝 #6

Open
shengq666 opened this issue Jun 28, 2020 · 4 comments
Open

6、深浅拷贝 #6

shengq666 opened this issue Jun 28, 2020 · 4 comments

Comments

@shengq666
Copy link
Owner

No description provided.

@shengq666
Copy link
Owner Author

shengq666 commented Jun 28, 2020

深浅拷贝出现的缘由:

js中基本类型是按值存储在栈内存中,而引用类型是按地址存储在堆内存中。
如果直接赋值,引用类型可能会得不到我们想要的结果

浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象还是会共享同一块内存。但深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象。

当 引用类型 存在多层数据的时候,浅拷贝克隆的不够彻底,只能克隆一层

@shengq666
Copy link
Owner Author

浅拷贝:concat、slice、展开运算符、Array.from()、Array.assign()

深拷贝:JSON.parse(JSOn.stringfy())
var arr = [1,2,3,null,'s1']
var arr1 = arr.concat()  // or var arr1 = arr.slice() or  var arr1 = [...arr]
arr1[0] = undefined
console.log(arr)  // [1, 2, 3, null, "s1"]
console.log(arr1)  //  [undefined, 2, 3, null, "s1"]
var arr = [1,2,3,null,{age:24},'ax']
var arr1 = [...arr]
arr1[4].age = 25
console.log(arr) // [1, 2, 3, null, {age:25}, "ax"]
let a = {
  age: 1
}
let b = Object.assign({}, a)
a.age = 2
console.log(b.age) // 1

JSON.parse(JSON.stringify(object))局限性

  • 会忽略 undefined
  • 会忽略 symbol
  • 不能序列化函数
  • 不能解决循环引用的对象

@shengq666
Copy link
Owner Author

浅拷贝的实现
遍历对象,把属性与值存到一个新的对象中

function shallowClone(obj) {
    if( typeof obj != 'object' ) { return }
    var newObj = obj instanceof Array ? []:{}
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = obj[key];
        }
     }
     return newObj;
}

@shengq666
Copy link
Owner Author

深拷贝

function deepClone(obj) {
  function isObject(o) {
    return (typeof o === 'object' || typeof o === 'function') && o !== null
  }
  if (!isObject(obj)) {
    throw new Error('非对象')
  }

  let isArray = Array.isArray(obj)
  let newObj = isArray ? [...obj] : { ...obj }
  Reflect.ownKeys(newObj).forEach(key => {
    newObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key]
  })

  return newObj
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant