簡體   English   中英

如何根據我在javascript中的循環迭代將字符串拆分為數組?

[英]How can I split a string into an array according to my loop iteration in javascript?

我試圖在我for-loop的每次迭代中將一個字符串split為一個數組。 就像一個字符串是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. 循環遍歷字符串數組並每次按索引 char 分割。
  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' ]
  ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM