var newData:String[] = [];
let word = "";
let Inctext = "1234567890123456789012345678901234567890123456789012345678901234567890";
for (let i = 0; i < Inctext.length; i )
{
word = Inctext[i]
console.log(word)
newData[i] = word
console.log(newData)
}
I want to store 15 string characters in an array index and next 15 characters in other index. Array index 0 = "123456789012345" Array index 1 = "678901234567890" and so on...
CodePudding user response:
const word = "1234567890123456789012345678901234567890123456789012345678901234567890";
const chunkedWord = [];
for (let i = 0; i < (word.length / 15); i ) {
const chunkStart = i * 15;
const chunkEnd = chunkStart 15;
chunkedWord[i] = word.slice(chunkStart, chunkEnd);
}
console.log(chunkedWord)
The for loop iterates n times, whereas n is the length of word divided by 15. Hence, each iteration deals with a 15 character chunk of word
. For each chunk we calculate its start and end. The start of a chunk is its position (starting from 0) in the chunk array multiplied by the chunk length (15). The end is the chunk start incremented by the chunk length (15).
Based on chunkStart
and chunkEnd
, we slice a 15 character chunk out of word
and assign it to the corresponding index of chunkedWord
. By doing word.length / 15
in the for loop, we make sure that chunkedWord has the right amount of indices.