首页 > 解决方案 > 如何在不嵌套的情况下多次将字符串拆分为数组?JavaScript

问题描述

我正在做一个练习(自学),其中我必须有一个数组,其中有一个字符串被插入 n 次。

我有这个

var splitTxt = [];

for(i=0 ; i<n ; i++)
  {
    splitTxt += text.split('');
  }

text是函数中给出的字符串。我环顾四周,但只看到有关如何将字符和其他字符串等添加到数组末尾的建议。

添加拆分通常会产生所需的结果,但是,当像这样循环它时,我在数组中的每个索引中都得到一个逗号。这里发生了什么,我该如何正确地做到这一点?

我可以做这个:

for(i=0 ; i<n ; i++)
  {
    splitTxt.push(text.split(''));
  }

但这会产生一个嵌套数组,这是不需要的。

我也可以这样做:

var secondChar = [].concat(...Array(n).fill(text.split('')));

但是,同样,嵌套数组。不过我喜欢这个,使用数组构造函数来搞乱它,非常聪明。@CertainPerformance在这里给出的答案

编辑:对不起,我不够清楚。我想将它多次拆分为数组,如下所示:

var text = "hello there!";
n = 3;

desired result: ["h","e","l","l","o"," ","t","h","e","r","e","!","h","e","l","l","o"," ","t","h","e","r","e","!","h","e","l","l","o"," ","t","h","e","r","e","!"]

标签: javascriptarrays

解决方案


看到你编辑后,实现你想要的最简单的方法可以在一行中完成:

console.log('hello there!'.repeat(3).split(''));


推荐阅读