Home > OS >  For Loop is not redefining what's supposed to be defined
For Loop is not redefining what's supposed to be defined

Time:03-21

I have this for loop in which I'm trying to replace an index in underlineArr with a character and whenever I try to redefine it so It saves the current variable so I'm able to access it and change it later, nothing is being saved, It keeps using the default array while I'm trying to get the newly edited array.

For Loop:

       const content = collected.content.toLowerCase();
           for (let i = 0; i < underlineArr.length; i  ) {
               msg = underlineArr[i] = word[i] == content && underlineArr[i] == "_" ? content : "_";
           }
           msg = underlineArr.join(" ");
           console.log(msg);

This is the underlineArr constant: https://i.stack.imgur.com/vtzj2.png

This is the word constant: "French Toast", Please note the constant is random from an array I created.

Lastly, collected.content is just a string returned.

The output: Output

Expected output:

_ r _ _ _ _ _ _ _ _ _ _
_ r e _ _ _ _ _ _ _ _ _
_ r e n _ _ _ _ _ _ _ _
_ r e n c _ _ _ _ _ _ _
.....

CodePudding user response:

Try to get the index of content character instead of assigning the entire string.

for (let i = 0; i < underlineArr.length; i  ) {
   underlineArr[i] = word[i] == content && underlineArr[i] == "_" ? content[i] : "_";
}

CodePudding user response:

What about this... Am I cold or hot on that unclear question?

let word = "French Toast".split("")
let underlineArr = Array(word.length).fill("_")
let result = []
word.forEach((char,i) => {
  let row = [...underlineArr]
  row[i] = word[i]
  result.push(row)
})

multiline = result.map(subarr => subarr.join(" ")).join("\n")

console.log(multiline)

CodePudding user response:

I'm unsure of what I did, but I'm pretty sure the previous code I had wouldn't save anything because it'd replace the saved values with _ and in order to fix this,

    for (let i = 0; i < underlineArr.length; i  ) {
                if (content !== word.toLowerCase()[i]) continue;
                underlineArr[i] = word.toLowerCase()[i];
            }
  • Related