Skip to content

js中对象的拷贝 #5

Description

@hans000

数组、类数组的拷贝(浅拷贝)

let [1, 2, 3, 4]

// 方式一
let copy = [...arr]

// 方式二
let copy = Array.prototype.slice.call(arr)

对象的拷贝(深拷贝)

// 代码实现
let copy = JSON.parse(JSON.stringify(obj))

//缺陷
// 不能拷贝类型为undefined、function、Symbol
// NaN视为null
// 循环引用会报错

简单的对象拷贝

// 代码实现
function simpleClone(obj) {
  let copy = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    const elt = obj[key];
    copy[key] = (typeof elt === 'object' && elt !== 'null')
      ? simpleClone(elt)
      : elt
  }
  return copy
}

// 缺陷
// 循环引用会爆栈RangeError

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions