Skip to content

structuredClone & js object deep copy / js deep clone  #33

@xgqfrms

Description

@xgqfrms

structuredClone & js object deep copy / js deep clone

structuredClone

const origin = {
  num: 1,
  arr: [2012, 2023],
  func: (v) => console.log(v),
  obj: {msg: 'bug'},
  date: new Date(`2012-01-01`),
  u: undefined,
  nil: null,
  nan: NaN,
  bool: true,
  str: 'string',
  s: Symbol(`s`),
  bi: BigInt(10**32),
  set: new Set([1, 2, 3]),
  map: new Map([['a', 11], ['b', 22], ['c', 33]]),
  // reg: /^0+/g,
  reg: new RegExp(/^0+/g),
};

https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm

structuredClone(value)
structuredClone(value, options)

bugs

image

image

image

Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': function (v) {console.log(v)} could not be cloned.

Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': Symbol(s) could not be cloned.
const origin = {
  num: 1,
  arr: [2012, 2023],
  // func: function (v) {console.log(v)},
  obj: {msg: 'bug'},
  date: new Date(`2012-01-01`),
  u: undefined,
  nil: null,
  nan: NaN,
  bool: true,
  str: 'string',
  // s: Symbol(`s`),
  bi: BigInt(10**32),
  set: new Set([1, 2, 3]),
  map: new Map([['a', 11], ['b', 22], ['c', 33]]),
  // reg: /^0+/g,
  reg: new RegExp(/^0+/g),
};


deepClone = structuredClone(origin);

image

refs

https://www.cnblogs.com/xgqfrms/p/17060969.html

https://juejin.cn/post/7080433165264748557

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions