/    Sign up×
Community /Pin to ProfileBookmark

Restarted my JS studies coz it was doing my head in :p

Can some please explain this for me?

[CODE]
if(email.indexOf(“@”) != -1){ alert(“You have an @ in your email address”); }[/CODE]

This code produces an alert if there is an @ in the input field. BUT… Why the != -1? Why not? == 1? I tried… It doesn’t work. It only works if I go, == 0

Just looking for an explanation as to why. Thanks in advance folks
?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@WolfShadeJan 18.2011 — -1 equals "false".

If there is not an index (0 or greater) then it doesn't exist, so the function returns -1.

^_^
Copy linkTweet thisAlerts:
@Hooded_VillianauthorJan 18.2011 — -1 equals "false".

If there is not an index (0 or greater) then it doesn't exist, so the function returns -1.

^_^[/QUOTE]


I see... And why does JS have to be so annoying as to be written like that. LoL.

I checked on http://www.w3schools.com/jsref/jsref_IndexOf.asp aswell, and it appears that indexOf() returns a number. So, exactly as you said, a positive number would be true and a negative, in this case -1, would be false.

Thanks WolfShade
Copy linkTweet thisAlerts:
@WolfShadeJan 18.2011 — No problem.

And the reason why it's like that is because it uses a 0-based index (the first position is 0) instead of a 1-based index (first position is 1.)

^_^
Copy linkTweet thisAlerts:
@Hooded_VillianauthorJan 18.2011 — No problem.

And the reason why it's like that is because it uses a 0-based index (the first position is 0) instead of a 1-based index (first position is 1.)

^_^[/QUOTE]


I see... Kind of like arrays? Starts at 0.

var myName = new Array();

myName[0] = "Alexis";

etc

So, if I said... indexOf("@") == 0, that would still be positive, provided an @ was found.

Thanks again...
×

Success!

Help @Hooded_Villian spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...