Tham chiếu API gạch dưới :
_.toArray(list)
Tạo một Mảng thực từ danh sách (bất kỳ thứ gì có thể được lặp lại). Hữu ích để chuyển đổi đối tượng đối số.
... hoặc trong trường hợp này, sao chép một mảng. Thử đi:
var _ = require('underscore');
var array1 = [{a:{b:{c:1}}},{b:{c:{a:2}}},{c:{a:{b:3}}}];
var array2 = _.toArray(array1);
console.log(array1 === array2); --> false
console.log(array1[0] === array2[0]); --> true
Sau đây là một phụ lục tôi đã tạo ra sau bình luận của Steve bên dưới -thx
function clone(thing, opts) {
var newObject = {};
if (thing instanceof Array) {
return thing.map(function (i) { return clone(i, opts); });
} else if (thing instanceof Date) {
return new Date(thing);
} else if (thing instanceof RegExp) {
return new RegExp(thing);
} else if (thing instanceof Function) {
return opts && opts.newFns ?
new Function('return ' + thing.toString())() :
thing;
} else if (thing instanceof Object) {
Object.keys(thing).forEach(function (key) {
newObject[key] = clone(thing[key], opts);
});
return newObject;
} else if ([ undefined, null ].indexOf(thing) > -1) {
return thing;
} else {
if (thing.constructor.name === 'Symbol') {
return Symbol(thing.toString()
.replace(/^Symbol\(/, '')
.slice(0, -1));
}
return thing.__proto__.constructor(thing);
}
}
var a = {
a: undefined,
b: null,
c: 'a',
d: 0,
e: Symbol('a'),
f: {},
g: { a:1 },
h: [],
i: [ { a:2 }, { a:3 } ],
j: [ 1, 2 ],
k: function (a) { return a; },
l: /[a-z]/g,
z: [ {
a: undefined,
b: null,
c: 'b',
d: 1,
e: Symbol(1),
f: {},
g: { b:2 },
h: { c:{ c:3 } },
i: { a:Symbol('b') },
j: { a:undefined, b:null },
k: [],
l: [ 1, [ 1, 2 ], [ [ 1, 2, 3 ] ] ],
m: function (a) { return !a; },
n: { a:function (a) { return !!a; } },
o: /(a|b)/i
} ]
};
var b = clone(a);
var c = clone(a, { newFns:true });