使用Underscore减少连接?

Ror*_*rro 1 javascript concatenation underscore.js

有人可以帮我解决这个问题吗?我正在尝试
使用(Underscore)_.reduce来连接数组中的所有字符串.

输入:

['x','y','z']
Run Code Online (Sandbox Code Playgroud)

输出:

'xyz'
Run Code Online (Sandbox Code Playgroud)

这是我开始的方式:

_.reduce(['x','y','z'], function(current, end) {
    return...
});
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

你可以Array.prototype.join在这里使用.它比reduce这种情况更有效率.

console.log(['x','y','z'].join(""));
// xyz
Run Code Online (Sandbox Code Playgroud)

但是如果你想使用_.reduce,你可以这样做

_.reduce(['x', 'y', 'z'], function(accumulator, currentItem) {
    return accumulator + currentItem;
});
// xyz
Run Code Online (Sandbox Code Playgroud)

_.reduce只是Array.prototype.reduce支持它的环境中的原生包装.您可以reduce这个答案中详细了解如何处理输入.

这是一个简短的解释.

由于没有传递给初始值_.reduce,因此集合中的第一个值将用作累加器值,并使用累加器值和第二个值调用该函数.所以,这个函数就是这样调用的

accumulator : 'x'
currentItem : 'y'
-----------------
accumulator : 'xy' (because returned value will be passed again as accumulator)
Run Code Online (Sandbox Code Playgroud)

在接下来的电话中,

accumulator : 'xy'
currentItem : 'z'
-----------------
accumulator : 'xyz' (since no elements left, accumulator will be returned)
Run Code Online (Sandbox Code Playgroud)