我想知道这是否是克隆变量的安全方法:

// 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]的值,则对象[0]的值将保持不变。

关于javascript - 这是克隆任何对象/功能/等的有效/安全方法吗?在ES6中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53291810/

10-10 22:48