Home > OS >  Very large string arrays not working as expected
Very large string arrays not working as expected

Time:03-06

I have an array with 58112 words. However, when I try to check if a word is in the list, it always returns false, except for the first word. I'm not going to post my code because that would be too large, but here is some of the main stuff:

isWord("a") //true
isWord("hello") //false??

function isWord(word) {
  word = word.toLowerCase();
  for (let i = 0; i < words.length; i  ) {
    if (word == words[i]) {
      return true;
    } else {
      return false;
    }
  }
}

words[] is the list of 58112 words. The first word is "a", of course. When I do isWord("a"), it returns true, like expected. If I do anything other than "a", It returns false. Why does this occur? Is it because I exceeded the maximum array limit? I don't think so.
The words I used are from this (I had to add the "a" and the "i" because they didn't have one).

CodePudding user response:

I noticed you made it

return false;

That would make it so that anything after the return statement does not execute (and as a result your code stops executing after one iteration). I would recommend replacing it with a print statement or storing the result in a Boolean variable and printing it elsewhere, OR maybe returning the Boolean variable so you don't have to change a lot of the other code. That can be done this way:

isWord("a") //true
isWord("hello") //false??

function isWord(word) {
  var boolean check = false;   //setting it to false by default removes the need for the "else" statement
  word = word.toLowerCase();
  for (let i = 0; i < words.length; i  ) {
    if (word == words[i]) {
      check = true;
    }
  }
  return check;
}

CodePudding user response:

I may be wrong, but I think this is because when you are checking whether the word is in the words array or not, in the first iteration of the array, if it finds that the word that you entered is 'a' which is the value of words[0], it returns true else if it isn't it returns false and exits out of the function. So essentially it only checks whether the element you entered is equal to 'a' or not.

CodePudding user response:

Here is a faster and more concise way to achieve the same functionality.

function isWord(word) {
    word = word.toLowerCase()
    var i = word.length;
    while (i--) {
       if (words[i] === word) {
           return true;
       }
    }
    return false;
}
  • Related