简体   繁体   English

如何在不嵌套的情况下多次将字符串拆分为数组? JavaScript的

[英]How do I split a string into an array multiple times without it being nested? JavaScript

I'm doing an exercise (self-study) in which I must have an array that has a string being inserted into it n times. 我正在做一个练习(自学),我必须有一个数组,其中插入一个字符串n次。

I have this 我有这个

var splitTxt = [];

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

text being the string given in the function. text是函数中给出的字符串。 I've looked around but I only ever see advice on how to add characters and other strings etc. to the ends of arrays. 我环顾四周,但我只看到如何在数组的末尾添加字符和其他字符串等的建议。

Adding split normally produces the desired result, however, when looping it like this, i get a comma in every index in the array. 添加split通常会产生所需的结果,但是,当像这样循环时,我会在数组的每个索引中得到一个逗号。 What is happening here, and how do I do it properly? 这里发生了什么,我该如何正确地做到这一点?

I can do this: 我可以做这个:

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

But that produces a nested array, not desired. 但是这产生了一个嵌套数组,不是所希望的。

I can also do this: 我也可以这样做:

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

But, again, nested array. 但是,再次,嵌套数组。 I like this one though, using the array constructor to mess with it, very clever. 我喜欢这个,使用数组构造函数来搞乱它,非常聪明。 An answer given by @CertainPerformance here @CertainPerformance 在这里给出了答案

EDIT: Sorry, I wasn't clear enough. 编辑:对不起,我不够清楚。 I'd like to split it into the array multiple times like so: 我想多次将它分成数组:

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","!"]

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

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

Wanted to see if I could do this without using repeat and split, and here is what I came up with. 想要看看我是否可以不使用重复和拆分来做到这一点,这就是我想出的。

 function mapx(text, x) { var myArray = []; for (var y = 0; y < x; y++) { myArray = myArray.concat(Array.prototype.map.call(text, i => i)); } return myArray; } var result = mapx('hello there!', 3); console.log(result); 

array.map and array.concat are pretty well supported in browsers. array.map和array.concat在浏览器中得到很好的支持。 You could use .split instead .map - in fact I believe split benchmarks faster than map in small arrays. 您可以使用.split而不是.map - 实际上我认为分割基准比在小数组中映射更快。 When objects get larger map has an advantage. 当对象变大时,地图有一个优势。

Based on your example, just repeat the text n times and then split it: 根据您的示例,只需重复文本n次,然后将其拆分:

 function splitText(text, n) { return text.repeat(n).split(''); } var result = splitText('hello there!', 3); console.log(result); 

Keep in mind that String.prototype.repeat isn't supported by older browsers, but it can be easily polyfilled. 请记住,旧版浏览器不支持String.prototype.repeat ,但可以轻松地将其填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM