variables - Dynamically calling upon similar objects in javascript? -


i apologize in advance title, had no idea how word i'm trying ask (and if similar question asked before, wouldn't have known how search it). have 4 similar objects in program, , such have differentiated them so:

var person1object = {     foo: [],     bar: [] } var person2object = {     foo: [],     bar: [] } var person3object = {     foo: [],     bar: [] } var person4object = {     foo: [],     bar: [] 

as variable counts 1 through 4 through function when button pressed, so:

var count = 1; function count() {     if (count < 4) {         i++;     } else {         = 1;     } } $("#button").on("click", function () { count(); }); 

i trying this:

person+count+object.foo.push("some value"); person+count+object.bar.push("some other value"); 

but when that, console says (and i'm assuming rightfully so) person not defined.

i have tried using array so:

var personobject = [person1object, person2object, person3object, person4object] personobject[count].foo.push("some value"); 

but not work either. also, avoid if statements if can.

how manipulate these objects without using bunch of if statements?

you can access objects dynamic names via window object (in browser anyway).

so should work:

window['person'+count+'object'].foo.push("some value"); window['person'+count+'object'].bar.push("some other value"); 

if needed in node, same thing use global instead, so:

global['person'+count+'object'].foo.push("some value"); global['person'+count+'object'].bar.push("some other value"); 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -