简体   繁体   English

如何遍历字符串,每次向数组添加1个额外的字符

[英]How to loop through string, adding 1 extra character to an array each time

I'm trying to use JS to loop through a string value while adding the first character and the following characters to an array. 我正在尝试使用JS在将第一个字符和随后的字符添加到数组时循环遍历字符串值。 This process repeats again with the next character. 下一个字符再次重复此过程。

For example, if I were to input ABCD then the array would turn out to be: 例如,如果我要输入ABCD,则该数组将变为:

[A, AB, ABC, ABCD, B, BC, BCD, C, CD, D] [A,AB,ABC,ABCD,B,BC,BCD,C,CD,D]

This will work: 这将起作用:

 var str = 'ABCD' var arr = [] for (var j = 0; j < str.length; j++) { for (var i = 0; i < str.length - j; i++) { arr.push(str.substr(j, i+1)) } } console.log(arr) 

you can split your problem into two small function first function combination of a single word then pass this function for every element in a single world an play with the substring params. 您可以将问题分解成两个小功能,第一个功能combination of a single word然后将该功能传递给single world的每个元素,并使用substring参数进行播放。

 const text = "ABCD"; const arrayOfCombination = []; const combinationWord = word => [...word].map((el, index) => word.substring(0, index + 1)); [...text].forEach((el, index) => arrayOfCombination.push(combinationWord(text.substring(index, text.length)))); console.log(arrayOfCombination.flat()) 

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

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