1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.