这是克隆任何 object/function/etc 的 valid/safe 方法吗?在 ES6 中?
Is this a valid/safe way to clone any object/function/etc. in ES6?
我想知道这是否是一种安全的克隆变量的方法:
// the original variable definition:
let varIWantToCopy = 'hello world'
// the clone variable's definition:
let {varIWantToCopy: cloneOfVarIWantToCopy} = {varIWantToCopy}
// mutating the original value:
varIWantToCopy = 'goodbye world'
// should log out 'hello world':
console.log(cloneOfVarIWantToCopy)
感谢您抽出宝贵时间查看此内容。
亲切的问候,
哈利
如果你真的想克隆一个对象,我认为你应该使用 lodash。
There are several clone functions in lodash that you can use depending on your requirements.
// or you can use lodash/clone
import cloneDeep from 'lodash/cloneDeep';
var objects = [{ 'a': 1 }, { 'b': 2 }];
var cloned = cloneDeep(objects);
console.log(cloned[0] === objects[0]); // this will be false
因此,如果您更改 cloned[0] 的值,object[0] 的值将不会更改。
我想知道这是否是一种安全的克隆变量的方法:
// the original variable definition:
let varIWantToCopy = 'hello world'
// the clone variable's definition:
let {varIWantToCopy: cloneOfVarIWantToCopy} = {varIWantToCopy}
// mutating the original value:
varIWantToCopy = 'goodbye world'
// should log out 'hello world':
console.log(cloneOfVarIWantToCopy)
感谢您抽出宝贵时间查看此内容。
亲切的问候,
哈利
如果你真的想克隆一个对象,我认为你应该使用 lodash。 There are several clone functions in lodash that you can use depending on your requirements.
// or you can use lodash/clone
import cloneDeep from 'lodash/cloneDeep';
var objects = [{ 'a': 1 }, { 'b': 2 }];
var cloned = cloneDeep(objects);
console.log(cloned[0] === objects[0]); // this will be false
因此,如果您更改 cloned[0] 的值,object[0] 的值将不会更改。