2

I'm doing some exercises and having a hard time figuring out why my code won't work, would be glad if someone can point me in the right direction. So my input is a string of numbers, which I .split to get an array of strings (so I can loop trough it). Then I want to compare if the strings are equal to the next one or not, and use it to do something (here I'm just printing out the status). Can't figure out what I did wrong, code below.

var line = "40 40 40 40 29 29 29 29 29 29 29 29 57 57 92 92 92 92 92 86 86";

line = line.split(" ");

for (x = 0; x < line.lenght; x++) {
  if (line[x] == line[x + 1]) {
    console.log("numbers are the same");
  } else if (line[x] !== line[x + 1]) {
    console.log("numbers aren't the same");
  }
}

3
  • 1
    * line.length - not lenght. Commented Mar 18, 2015 at 9:53
  • also the else if() is useless, just go for an else() Commented Mar 18, 2015 at 9:56
  • for (x = 0; x < line.length - 1; x++)( typo and dereference beyond upper array bound). Consider using the type-safe equality test (=== instead of ==). Commented Mar 18, 2015 at 9:57

2 Answers 2

1

You made a typo: length instead of lenght and your code is good to go.

Sign up to request clarification or add additional context in comments.

1 Comment

accepted JohnIdol's anwser, since he was a bit quicker
0

You misspelled length so that's why it's not logging plus when you're on the last array item you'll go out of bounds with line[x + 1].

2 Comments

well if it goes out of bound, it'll just return number not the same, because there's nothing there to compare it to, right?
That's technically right in this example but in general do not rely on things like that, it's not comparing numbers/strings anymore because you're looking for an array element that doesn't exist (that will return "undefined").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.