Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #15873

Re: Simple array reference question

From Stefan Weiss <krewecherl@gmail.com>
Newsgroups comp.lang.javascript
Subject Re: Simple array reference question
Date 2012-09-12 16:03 +0200
Organization albasani.net
Message-ID <k2q4nb$l72$1@news.albasani.net> (permalink)
References <k2pn0l$n7v$1@news.albasani.net> <50506600$0$21231$ba4acef3@reader.news.orange.fr> <k2pqfc$uus$1@news.albasani.net>

Show all headers | View raw


On 2012-09-12 13:08, Tuxedo wrote:
> SAM wrote:
>> > When accessing a page including a parameter, such as 'page.html?fish'
>> > and placing the string in a 'param' variable, how can the fish array be
>> > returned?
...
>> alert(eval(param));
>> 
>> alert('array = ' + param +
>>        '\nelement 1 = ' + eval(param)[1]
>>       );
>> 
> 
> Many thanks for the eval tricks!

This is the very worst of all possible uses for eval. A user-supplied
parameter which is blindly eval()ed, what could possibly go wrong?

When you find that you need to access a variable based on a string
containing the variable's name, that's almost always an indication of
bad design. Yes, you could access it with this[param] in the global
scope, but it would be much cleaner to create a dedicated container for
those values:

  var data = {
      birds: ["fowl", "penguin", "sparrow"],
      fish: ["crayfish", "jellyfish"]
  };

  var param = location.search.substring(1);
  if (data.hasOwnProperty(param)) {
      // safe to use data[param]
  } else if (param) {
      // handle invalid user input
  } else {
      // no input
  }

The this[param] approach is not much better than the often abused
"register_globals" setting in PHP.

- stefan

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Simple array reference question Tuxedo <tuxedo@mailinator.com> - 2012-09-12 12:09 +0200
  Re: Simple array reference question SAM <stephanemoriaux.NoAdmin@wanadoo.fr.invalid> - 2012-09-12 12:37 +0200
    Re: Simple array reference question Tuxedo <tuxedo@mailinator.com> - 2012-09-12 13:08 +0200
      Re: Simple array reference question Stefan Weiss <krewecherl@gmail.com> - 2012-09-12 16:03 +0200
        Re: Simple array reference question Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-12 16:42 +0200
  Re: Simple array reference question marat.rheingold@gmail.com - 2012-09-12 05:34 -0700
    Re: Simple array reference question Tuxedo <tuxedo@mailinator.com> - 2012-09-12 15:10 +0200
    Re: Simple array reference question Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-09-12 15:36 +0200
      Re: Simple array reference question Tuxedo <tuxedo@mailinator.com> - 2012-09-12 20:59 +0200

csiph-web