Reputation: 15
I'm trying to figure out why my output is not correct it kinda works but still has some faults in the loop I can't seem to find why. I know there are better ways to do this but i want to learn what went wrong in this loop.
So first it ask a sentence second question is to replace 2 letters like : a e third question is to replace it with like : o u
I then split the karakters and put the sentence in an array. The loop checks every letter in the array and if it comes across one of the letters it should replace it with the one found.
var input = prompt("geef een zin ?");
var zin = [];
zin = input.split("");
var inn = prompt("welke karakters wil je veranderen?");
var karaktersinn = inn.split("");
var outt = prompt("in welke letters wil je ze veranderen?");
var karatersout = outt.split("");
var output = "";
console.log(input);
for (var i = 0;i < input.length-1;i++){
if (zin[i] == karaktersinn[0]){
output += karatersout[0]
}if (zin[i] == karaktersinn[2]){
output += karatersout[2]
}else{
output += zin[i];
}
}
console.log(output);
console.log(zin)
console.log(karaktersinn)
console.log((karatersout))
Upvotes: 0
Views: 32
Reputation: 20626
Your if conditions are structured like this :
if
if
else
This means you have two if else blocks. So regardless of what happens in the first block, the second block will always be checked, and one of the the last conditions will run
You need an if-else. So at one time only one of the three conditions run.
var input = prompt("geef een zin ?");
var zin = [];
zin = input.split("");
var inn = prompt("welke karakters wil je veranderen?");
var karaktersinn = inn.split("");
var outt = prompt("in welke letters wil je ze veranderen?");
var karatersout = outt.split("");
var output = "";
console.log(input);
for (var i = 0;i < input.length;i++){
if (zin[i] == karaktersinn[0]){
output += karatersout[0]
}else if (zin[i] == karaktersinn[2]){
output += karatersout[2]
}else{
output += zin[i];
}
}
console.log(output);
console.log(zin)
console.log(karaktersinn)
console.log((karatersout))
Also you are running one less iteration of the loop. Fixed that.
Upvotes: 1