我如何分割字符串成一个数组根据我的循环迭代在javascript?



我试图将split字符串转换为每次迭代for-loop的数组。例如,如果字符串是1234,那么我想将其拆分为['12','34']

我想把这个字符串分成不同的方式。比如['1','2','3','4'],['123','4']等等。但我不知道该怎么做?

The string "31173" can be split into prime numbers in 6 ways:
[3, 11, 7, 3]
[3, 11, 73]
[31, 17, 3]
[31, 173]
[311, 7, 3]
[311, 73]
let k=1;
for(let i=0; i<inputStr.length; i++){

if(k<inputStr.length){
// split string 
let splittedNums=inputStr.split('',i+k);
for(let j=0; j<splittedNums.length; j++){
if(isPrime(splittedNums[j]))
result.push([splittedNums[j]]);

}
}
k++;
}

我尝试使用split()函数,但当我从文档中了解到它将使用限制来分割字符串并返回它。所以,它不会像这样工作。

我想分割并检查数字是否为素数,然后将其推入数组。最后,我将得到包含素数的子数组

我怎么能分割字符串,然后把它变成一个数组像这样在javascript?

解决方案之一。我试图在评论中解释这些步骤,但只是总结一下

  1. 将字符串转换为数组
  2. 循环遍历字符串数组并每次按索引字符分割。
  3. 通过将分隔符连接到数组的最后一项来恢复丢失的分隔符。

const str = "12345678";
// split the array
const strArr = str.split("");
// loop through the str array and split with a character got by index
const splitedStr = strArr.map((each, index) => {
// this will split the string by index char but we will lose the separator passed
const withoutSeparator = str.split(str[index]); 
const lastIndex = withoutSeparator.length - 1; // get last element of array
// to get the separator back.
// basically we are appending the separator char to last item of the array 
withoutSeparator[lastIndex] = str[index] + withoutSeparator[lastIndex];
return withoutSeparator;
});
console.log({ splitedStr });

输出
{
splitedStr: [
[ '', '12345678' ],
[ '1', '2345678' ],
[ '12', '345678' ],
[ '123', '45678' ],
[ '1234', '5678' ],
[ '12345', '678' ],
[ '123456', '78' ],
[ '1234567', '8' ]
]
}

最新更新