javascript - Difference between Object.assign and using [...] syntax? -
i have code here , wondering if same thing or different. pretty sure these both suppose same wasnt sure if doing right.
let zonecomment = updatedmap[action.comment.zone] ? [...updatedmap[action.comment.zone]] : [];
let zonecomment = updatedmap[action.comment.zone] ? object.assign([], updatedmap[action.comment.zone]) : [];
if these same should use or matter? want use best practice if opinion of better please state so.
in particular case not same.
the reason have array, not object.
doing ...
on array spread out elements in array (but not properties)
doing object.assign
expects object treat array object , copy enumerable own properties it, not elements:
const = [1, 2, 3] a.test = 'example' const 1 = [...a] // [1, 2, 3] const 2 = object.assign([], a) // { '0': 1, '1': 2, '2': 3, 'test': 'example' } console.log('\none'); (let prop in one) { console.log(prop); } console.log('\ntwo'); (let prop in two) { console.log(prop); }
however, if compare ...
operator applied on object object.assign
, same:
// same result const = { name: 'test' } console.log({ ...a }) console.log(object.assign({}, a))
except ...
creates new object object.assign
allows mutate existing object.
// same result const = { name: 'test' } const b = { ...a, name: 'change' }; console.log(a.name); // test object.assign(a, { name: 'change'}) console.log(a.name); // change
keep in mind object.assign
part of language whereas object spread still proposal , require preprocessing step (transpilation) tool babel.
wiki
Comments
Post a Comment