自动创建Javascript对象并将其存储在另一个对象中

时间:2013-08-11 17:33:55

标签: javascript variables javascript-objects web-storage

所以我想创建一个能够生成名称的javascript函数,然后将其设置为变量,然后创建一个对象。在下面的代码中,我想到了一个输入表单的示例,虽然我只显示了我的Javascript。假设用户已输入一次数据以创建对象咖啡。阅读评论

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");
    }
}

当然我并没有完全使用这个例子。我清楚地使用它,我对这种功能的实际用途是用于基本的客户端存储输出,用于在我的服务器脚本上加载CAS,返回更多客户端脚本并在其上加载自定义S(CC)AI-S / API浏览器。

2 个答案:

答案 0 :(得分:1)

这实际上是JavaScript的最佳方面之一。

假设您将所有这些用户生成的对象保留在通用列表中,例如:

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

有趣的是,现在您可以通过两种方式阅读coffee:使用objList.coffee和使用objList['coffee']。写作也是如此;所以我们可以将示例重写为:

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

瞧!您现在基本上使用字符串来标识变量。嗯,有点 - 它们不再是变量,它们是JS对象的属性。但仍然。

答案 1 :(得分:0)

您可以在JavaScript中为对象属性执行此操作:

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

但是,如果用“变量”表示“用var定义的符号或作为函数参数”,则不能以这种方式创建变量。