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


Groups > comp.lang.javascript > #33677

Re: Reference var in (function(){})()

Newsgroups comp.lang.javascript
Subject Re: Reference var in (function(){})()
From "Evertjan." <exxjxw.hannivoort@inter.nl.net>
References <KZ-dnfr95s94f-LEnZ2dnUU7-bnNnZ2d@westnet.com.au>
Date 2017-08-01 09:39 +0200
Message-ID <XnsA7C4622AC71A4eejj99@194.109.6.166> (permalink)

Show all headers | View raw


Andrew Poulos <ap_prog@hotmail.com> wrote on 01 Aug 2017 in 
comp.lang.javascript:

> There's some code that looks like
> 
> var con = (function() {

The encapseling has nothing to do with your Q, it seems.

>    var opt0 = {},
>        opt1 = {},
>        opt2 = {},
>        opt3 = {},
>        ...
> 
>    function x() {
>      //
>    }
>})()
> 
> Within the function x I need to reference each of the (many) "opt" 
> objects. I'd like to reference them in a for loop e.g.
> 
> for (i = 0; i < len; i++) {
>    eval("opt" + i) = ...
>}
> 
> but how can I do it without using eval?

eval is evil!

Use an array for series of numbered variables.

'use strict';
let opt = [], i;
opt[0] = {};
opt[1] = {};
opt[2] = {};
opt[3] = {};
function x(ob) {
	for (i = 0; i < ob.length; i++)
		ob[i].blah = 'rrr-' + i;
};
x(opt);
alert('>>>> ' + opt[3].blah);


-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

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


Thread

Reference var in (function(){})() Andrew Poulos <ap_prog@hotmail.com> - 2017-08-01 12:09 +1000
  Re: Reference var in (function(){})() "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2017-08-01 09:39 +0200
  Re: Reference var in (function(){})() Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2017-08-01 12:40 +0200
    Re: Reference var in (function(){})() Andrew Poulos <ap_prog@hotmail.com> - 2017-08-02 14:06 +1000
      Re: Reference var in (function(){})() Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2017-08-02 11:38 +0200
    Re: Reference var in (function(){})() Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2017-08-02 11:33 +0200

csiph-web