javascript - 如何在不嵌套的情况下多次将字符串拆分为数组?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","!"]
解决方案
看到你编辑后,实现你想要的最简单的方法可以在一行中完成:
console.log('hello there!'.repeat(3).split(''));
推荐阅读
- arrays - 打字稿:类型“数字”不能用作索引类型
- python-3.x - Gtk - Pixbuf.new_from_stream_at_scale_async 正在阻塞 UI
- sql - 如何检查动态列名是否为空
- javascript - 传单:如何将多边形与 GeoJson 合并?使用 Javascript
- reactjs - i18n 与 React - 如何为特定语言环境创建 .json 文件?
- prometheus - 从 grafana 中的计数器指标计算值
- python - matplotlib 上的图形编辑
- animation - 如何制作像苹果的 AR 彩蛋一样的 3D 动画?
- java - JavaFX 中的文本字段历史记录
- javascript - html表创建问题