【问题标题】:How to join array with different separator in JavaScript?如何在 JavaScript 中加入具有不同分隔符的数组?
【发布时间】: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


【解决方案1】:

你可以这样做:

// 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)

【讨论】:

    【解决方案2】:

    您可以通过为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 =&gt; (a, b) =&gt; [a, b].join(separators[++i, i%= separators.length]))(-1) 可以是 (a, b, i) =&gt; [a, b].join(separators[i]) ;)
    • @VLAZ,索引从一开始。
    • 你是对的!对不起,我错过了。但后来它是[i-1] 而不是[i]。不过,我确实很欣赏这里的 Scheme 风格。
    【解决方案3】:

    假设分隔符是随机的并且不包含任何逻辑。你可以看看下面的代码:

    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))
    

    如果这对您有帮助,请告诉我!快乐编码!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多