Pergunta

So I'm wanting to create a javascript function that is able to generate names and then set it as an variable to then create an object with. In the code below I thought up an example of entering a form though I am only showing my Javascript. Pretend the user already entered data once to create the object coffee. READ COMMENTS

function object(a,b){
    this.validate = 1
    this.one = a
    this.two = b
    if(z == "undefined"){
        var z = 0;
    }else{
        z = z++;
        gen(z);
    }
}


/* 
   Need a function that is able to generate generate names and set them as a variable
   This case for example the name of the object I'm trying to generate is coffee3
*/
function gen(x){
    if(coffee.validate != "undefined"){
        for(x, x < (x++), x++){
            var y = x.toString();
            y = "coffee" + y;

            /* 
               Turning the string value stored in y currently, say coffee3 for example,
               into a variable named coffee3 and gets new object("caramel", "milk")

               Also a code to store an object inside the sessionStorage object.

               if(typeof(Storage)!=="undefined")

               to check storage first of course
            */

        }
    }else{
        var coffee = new object("stuff", "input");
    }
}

Of course I'm not using this example exactly. I used it for clarity, my real usage for such a function will be for basic client side storage output for loading a CAS on my sever scripts that returns more client side script and loads a custom S(CC)AI-S/API on ones browser.

Foi útil?

Solução

This is actually one of the best aspects of JavaScript.

Let's say you keep all those user-generated objects into a generic list, for example:

objList = {};
objList.coffee = new object("stuff", "input");

Interestingly, now you can read coffee in two ways: by using objList.coffee and by using objList['coffee']. The same is true for writing; so we can rewrite the example as:

objList = {};
objList['coffee'] = new object("stuff", "input");

And voilà! You are now basically using strings to identify variables. Well, sort of - they're not variables anymore, they're properties on a JS object. But still.

Outras dicas

You can do that in JavaScript for object properties:

var someObject = {};
// ...
someObject[ "someString" + something ] = "hello world";

You cannot, however, create variables that way, if by "variable" you mean "symbol defined with var or as a function parameter".

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top