xgqfrms / learning-javascript-with-mdn

Learning JavaScript with MDN / 使用 MDN 学习 JavaScript
https://learning-javascript-with-mdn.xgqfrms.xyz
MIT License
1 stars 0 forks source link

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

Open xgqfrms opened 1 year ago

xgqfrms commented 1 year ago

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