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

数组深浅拷贝 #60

Open
Lee981265 opened this issue Jan 20, 2021 · 0 comments
Open

数组深浅拷贝 #60

Lee981265 opened this issue Jan 20, 2021 · 0 comments

Comments

@Lee981265
Copy link
Member

Lee981265 commented Jan 20, 2021

数组的浅拷贝

拓展运算符 (数组 字符串 对象皆可操作)

// 拷贝a
let a = [1,2]
let b = [...a]  // [1,2]

// 字符串转数组
let str = 'hello'
let arr = [...a] // ['h','e','l','l','e']

// 对象拷贝
let obj = {a:1,b:2}
let newObj = {...obj} // {a:1,b:2}

slice

let arr = [1,2]
let newArr = arr.slice()

concat

let arr = [1,2]
let newArr = arr.concat()

JSON序列化 不建议

JSON.parse(JSON.stringify(obj))

数组的深拷贝

 var c = [{a:1},{b:2}]
 var d = [...c.map(_ => ({...c}))]
copyArray(arr) {
    var newArr = arr.constructor === Array ? [] : {};
    if (typeof arr !== 'object') {
      return;
    }
    for (var i in arr) {
      newArr[i] = typeof arr[i] === 'object' ? this.copyArray(arr[i]) : arr[i];
    }
    return newArr;
  }
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