简体   繁体   English

Object.assign递归无法正常工作

[英]Object.assign recursive does not work as expected

I have the following function: 我有以下功能:

 const test = (i, o) => { if (i < 1) return o else return Object.assign(o, test(i - 1, ({ value: i, label: i }))) } console.log(test(5, ({}))) 

And i except it to print: 我除了打印它:

[
    { value: '1', label: '1' },
    { value: '2', label: '2' },
    { value: '3', label: '3' },
    { value: '4', label: '4' },
    { value: '5', label: '5' }
]

However the result is: 但是结果是:

{ value: 1, label: 1 }

What's wrong with recursive Object.assign? 递归Object.assign有什么问题?

The only way this could make sense is having an array as your result. 这可能有意义的唯一方法是将数组作为结果。

Here's a possible solution: 这是一个可能的解决方案:

 function test(length) { return [...Array(length).keys()] .map(i => ({value: i + 1, label: i + 1})) } console.log(test(5)); 

如果要在此处递归:

 const test = (i, o) => (i ? test(i - 1, o) : []).concat(Object.assign({}, o, { value: i, label: i }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM