【发布时间】:2020-06-18 18:15:48
【问题描述】:
var array = ["Red", "Green", "White", "Black", "Gray"];
document.write(array.join("+"));
我希望它像这样输出:Red+Green-White*Black#Gray
【问题讨论】:
-
您可以使用
reduce方法来做到这一点。
标签: javascript separator
var array = ["Red", "Green", "White", "Black", "Gray"];
document.write(array.join("+"));
我希望它像这样输出:Red+Green-White*Black#Gray
【问题讨论】:
reduce 方法来做到这一点。
标签: javascript separator
你可以这样做:
// your initial array of elements to join
var array = ["Red", "Green", "White", "Black", "Gray"];
// new list of separators to use
var separators = ["+","-","*","#"];
var joined = array.reduce((output, elem, index) => {
// always join the next element
output += elem;
// add next separator, if we're not at the final element in the array
if (index < array.length - 1) output += separators[index];
// return the current edits
return output;
}, '')
console.log(joined)
【讨论】:
您可以通过为glue 获取数组来减少。
var array = ["Red", "Green", "White", "Black", "Gray"],
glue = ['+', '-', '*', '#'],
result = array.reduce((a, b, i) => [a, b].join(glue[(i - 1) % glue.length]));
console.log(result);
【讨论】:
(i => (a, b) => [a, b].join(separators[++i, i%= separators.length]))(-1) 可以是 (a, b, i) => [a, b].join(separators[i]) ;)
[i-1] 而不是[i]。不过,我确实很欣赏这里的 Scheme 风格。
假设分隔符是随机的并且不包含任何逻辑。你可以看看下面的代码:
var chars = ['a', 'b', 'c', 'd'];
var delimiters = ['+', '-', '*', '#'];
function customJoin(resultantStr, num) {
let delimiter = delimiters[Math.floor(Math.random()*delimiters.length)];
return resultantStr+delimiter+num;
}
console.log(chars.reduce(customJoin))
如果这对您有帮助,请告诉我!快乐编码!
【讨论】: