View Full Version : Can someone help me to understand this code?

12-09-2011, 08:43 PM
I have seen this code-piece different places - to use to make a webpage redirect if it is a mobilephone.
I don't quit understand the code - especially the line:
if (redirectagent.indexOf(redirect_devices[i]) != -1)

- why -1 ? Please help me - I would be so thankful.

<script language=javascript>
var redirectagent = navigator.userAgent.toLowerCase();
var redirect_devices = ['vnd.wap.xhtml+xml', 'sony', 'symbian', 'nokia', 'samsung', 'mobile', 'windows ce', 'epoc', 'nitro', 'j2me', 'midp-', 'cldc-', 'netfront', 'mot', 'up.browser', 'up.link', 'audiovox', 'blackberry', 'ericsson', 'panasonic', 'philips', 'sanyo', 'sharp', 'sie-', 'portalmmm', 'blazer', 'avantgo', 'danger', 'palm', 'series60', 'palmsource', 'smartphone', 'rover', 'au-mic', 'alcatel', 'ericy', 'vodafone', 'wap1', 'wap2', 'teleca',, 'lge', 'lg-', 'iphone', 'android', 'htc', 'dream', 'webos', 'bolt', ];
for (var i in redirect_devices) {
if (redirectagent.indexOf(redirect_devices[i]) != -1) {

Old Pedant
12-10-2011, 04:13 AM
The indexOf method returns -1 if the text you are searching for is *NOT* found.

So by saying != -1 that is really saying "if the given text is found anywhere in the string...".

It's kind of weird coding. If the useragent string contained, for example, "mot" at *ANY* place in the string (e.g., "Mosilla FireFox with remote scripting support") then it will count as "found".

low tech
12-10-2011, 07:20 AM

why -1 ?
This post #5 may also help to claify things if you are still a little unsure about what indexOf does and why it returns -1