concat in reduce不工作?

时间:2018-05-26 23:57:02

标签: javascript arrays reduce

我正在尝试使用Array.reduce()来转换如下所示的字符串:

'React, {PureComponent, Fragment}'

进入这样的数组:

['React', 'PureComponent', 'Fragment']

要做到这一点,我正在使用这样的递归Array.reduce()

const str = 'React, {PureComponent, Fragment}';

const moduleFinder = (acc, curr) => {
    if (curr.charAt(0) === '{') {
        const insideStr = curr.substring(curr.indexOf("{")+1, curr.indexOf("}"));
        const insideModules = insideStr.split(',').map(e => e.trim());
        return acc.concat(insideModules.reduce(moduleFinder, []));
    } else {
        acc.push(curr);
        return acc;
    }
}


console.log(str.split(',').map(e => e.trim()).reduce(moduleFinder, []));

但是,我一直在Maximum call stack exceeded

我做错了什么?

1 个答案:

答案 0 :(得分:6)

我觉得你可能在这里做得太多了。这个简单的功能可以做你想要的:

let str = 'React, {PureComponent, Fragment}';

function replaceAndSplit(str) {
    return  str.replace(/{|}/g, '').split(',').map(e => e.trim());
}
console.log(replaceAndSplit(str));