1

In this code I created objects, which contain adjectives, or nouns in different gender. I also typed "beautiful maxim", and despite the fact that EnAdjectives has "beautiful" and "maxim" belongs to "EnMaleNouns", else statement executes.

let EnMaleNouns = {...};
let EnAdjectives = {...};

function conj() {
    let sentence = document.getElementById("input_one").value.split(" ").filter(item => item != "")
    let final = [];
    for (let word in sentence) {
        for (let key in EnAdjectives) {
            if (sentence[word] == key && sentence[++word] in EnMaleNouns) {
                //do something
            } else {
                //do something
            }
        }
    }
}

Can anyone tell me how to fix that, and why this is happening?

Hacker man
  • 45
  • 5
  • 1
    probably because you use `++word` in every test ... use `word+1` instead and refactor the code so it's not doing `++word` so many times – Jaromanda X May 02 '20 at 07:56
  • I tried, but it didn't work( – Hacker man May 02 '20 at 08:02
  • well, that suggests none of the conditions are met - should they be? perhaps `console.log(sentence[word], sentence[word_1] in EnMaleNouns, sentence[word_1] in EnFemaleNouns, sentence[word_1] in EnNeuterNouns)` before the first if, and see if the result is what you expect – Jaromanda X May 02 '20 at 08:04
  • Because you `break;` on every branch of the if statement you only execute both loops once. Maybe that helps – Max May 02 '20 at 08:19
  • https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea – Bergi May 02 '20 at 08:42

1 Answers1

0

The inner loop is a for in loop. So key will be holding index position as values i.e key = [0,1]. So in your if condition it is compared as 'beautiful' == 0 which will never be true. So the else block is executing everytime.


Solution: Use a for of loop for your inner loop as

for(let key of EnAdjectives)
Hemant Halwai
  • 396
  • 2
  • 8