我试图使用过滤器和映射的概念,而不是使用{for}循环遍历数组。

这是我的旧代码。我正在传递一个数组来过滤和组合匹配的字符串。

function oldFunction(data) {
    let dataDeleted = '';
    let each
    for (each of data) {
        if (each.includes('_DELETE')) {
            dataDeleted = dataDeleted + each.substring(0, each.length - 7) + '###';
        }
    }
    dataDeleted = dataDeleted;
    console.log(dataDeleted);
}

oldFunction(['meow_DELETE', 'haga', 'Neigh_DELETE']);


输出为:'meow###Neigh###'

现在,当我尝试使用“过滤器”和“减少”方法时,它似乎不起作用:

function newMethod(data) {

    const dataDeleted = data
        .filter(d => d.includes('_DELETE'))
        .reduce((deletedData, d) => {
            deletedData.concat(`${d}### `);
        }, '');

    console.log(dataDeleted);
    return dataDeleted;

}


这将返回“未定义”。有指针吗?提前致谢。

最佳答案

我相信您只需要在化简函数中return数据即可。

.reduce((deletedData, d) => {
   return deletedData.concat(`${d}### `);
}, '')


或使用速记版本:

.reduce((deletedData, d) => deletedData.concat(`${d}### `), '')

10-06 04:03