使用Underscore减少连接?

时间:2015-02-22 09:30:59

标签: javascript underscore.js concatenation

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

输入:

['x','y','z']

输出:

'xyz'

这是我开始的方式:

_.reduce(['x','y','z'], function(current, end) {
    return...
});

1 个答案:

答案 0 :(得分:5)

您可以在此处使用Array.prototype.join。对于这种情况,它比reduce更有效。

console.log(['x','y','z'].join(""));
// xyz

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

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

_.reduce只是支持它的环境中的本地Array.prototype.reduce的包装器。您可以详细了解reduce如何处理来自this answer的输入。

这是一个简短的解释。

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

accumulator : 'x'
currentItem : 'y'
-----------------
accumulator : 'xy' (because returned value will be passed again as accumulator)

并在下次通话中

accumulator : 'xy'
currentItem : 'z'
-----------------
accumulator : 'xyz' (since no elements left, accumulator will be returned)