简体   繁体   中英

temp variable not storing the modified String value

I am very new to JavaScript and I am trying to complete an exercise which I have to replace all the vowels in sentence variable with the index of the elements in the vowels array.

I have made a temp variable to hold the modified sentence. It does not work, but when I change temp to sentence (the original variable itself), the code then works.

May I know why does using the temp variable not work? Shouldn't it assign the modified sentence variable to temp ? Here is my code below. The output that I am looking for is: "2 l3v1 j0v0scr2pt", but I got "i love javascript" instead.

 let sentence = "I love JavaScript"; let temp; let vowels = ["a", "e", "i", "o", "u"]; vowels.forEach((currentValue, index) => { temp = sentence.toLowerCase().replaceAll(currentValue, index); }) console.log(temp);

Here at each iteration you are assigning a new value to temp variable. In the final iteration, since "u" is not present in the sentence you get the same value "I love Javascript". Instead of assigning the result to a temp variable, if you assign it to the variable sentence, you can get the expected result.

 let sentence = "I love JavaScript"; let vowels = ["a", "e", "i", "o", "u"]; vowels.forEach((currentValue, index) => { sentence = sentence.toLowerCase().replaceAll(currentValue, index); }); console.log(sentence);

You can use a JS code sandbox like this to try out. Debugging always helps.

There is no u in the sentence, therefore you can't really see what happened. Move o to the last place, then you'll see the result.

Basically, the problem here is that you are overwriting your temp variable in each loop iteration with a single change from the original variable. Instead, you need accumulate the changes, aka work on temp variable only. (for that you'll need initially copy the original variable value into temp)

 let sentence = "I love JavaScript"; let temp = sentence; //copy original value let vowels = ["a", "e", "i", "o", "u"]; vowels.forEach((currentValue, index) => { temp = temp.toLowerCase().replaceAll(currentValue, index); }) console.log(temp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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