Object.assign(…as) changes input parameter

后端 未结 1 1821
感情败类
感情败类 2021-01-21 02:12

Object.assign(...as) appears to change the input parameter. Example:

const as = [{a:1}, {b:2}, {c:3}];
const aObj = Object.assign(...as);


        
相关标签:
1条回答
  • 2021-01-21 02:41

    Object.assign is not a pure function, it writes over its first argument target.

    Here is its entry on MDN:

    Object.assign(target, ...sources)

    Parameters

    target

    The target object — what to apply the sources’ properties to, which is returned after it is modified.

    sources

    The source object(s) — objects containing the properties you want to apply.

    Return value

    The target object.

    The key phrase is "[the target] is returned after it is modified". To avoid this, pass an empty object literal {} as first argument:

    const aObj = Object.assign({}, ...as);
    
    0 讨论(0)
提交回复
热议问题