अंडरस्कोर एपीआई संदर्भ :
_.toArray(list)
सूची से एक वास्तविक ऐरे बनाता है (कुछ भी जो इसे खत्म किया जा सकता है)। तर्क वस्तु को प्रसारित करने के लिए उपयोगी है।
... या इस मामले में, एक सरणी का क्लोनिंग । इसे इस्तेमाल करे:
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
निम्नलिखित एक परिशिष्ट है जिसे मैंने स्टीव के नीचे -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 });