【问题标题】:Make from array string with length < 16从长度 < 16 的数组字符串生成
【发布时间】:2020-11-04 20:55:24
【问题描述】:

我有这个数组["Brad", "came", "to", "dinner", "with", "us"]

Brad came to dinner with us (27 chars > 16) 所以我需要将其拆分为 2 个字符串:

Brad came to
dinner with us

单词不能切片

let inpt=["Brad", "came", "to", "dinner", "with", "us"]
op=[]
for(i of inpt) if (op.join('').length+i.length <16) {op.push(i)} else break
console.log(op.join(' '))

这将返回我的第一部分,但如果我的输入数组(字符串)长于 16+16+16...,我如何获得第二部分和其他部分......

【问题讨论】:

标签: javascript arrays reduce


【解决方案1】:

空格连接后,使用正则表达式匹配最多16个字符,后跟空格或字符串结尾:

let inpt=["Brad", "came", "to", "dinner", "with", "us"];
const str = inpt.join(' ');
const matches = str.match(/.{1,16}(?: |$)/g);
console.log(matches);

【讨论】:

    【解决方案2】:

    也可以通过 Array.reduce 来完成:

    let inpt=["Brad", "came", "to", "dinner", "with", "us"];
    
    let out = inpt.reduce((acc, el) => {
      let l = acc.length;
      if (l === 0 || (acc[l - 1] + el).length > 15) {
        acc[l] = el;
      } else {
        acc[l - 1] += " " + el;
      }
      return acc;
    }, []);
    
    console.log(out);

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 2015-07-05
      • 2019-07-24
      • 2012-08-16
      • 1970-01-01
      • 2023-03-26
      • 2016-05-06
      • 2018-01-25
      相关资源
      最近更新 更多