【发布时间】:2016-05-20 22:14:37
【问题描述】:
几天前,我正在玩一些 js,当我想到我是否可以自动化对象嵌套的问题时。当然,我还是个新手,所以我还没有走得太远。
但我得到的是这样的:
var a = {};
var stso = ""; storing the second object
function sto(b) { // start the object
a[b] = {};
stso = b;
}
function nmo(...objs) { // nesting more object
console.log(objs[0]);
if(objs.length) { // checking to see that I have at least one variable before proceding
for(i = 0; i < objs.length; i++) { // looping through arguments
a[stso][objs[i]] = {}; // and now I would have to repeat one more more for lever for every argument, meaning, the deeper I want to go into the object, the more nested for loops I have to make.
}
}
}
sto("b");
nmo("c");
a.b.c = "Happy ending!";
console.log(a.b.c); // It seems we still dont have a happy ending
// and as a second example
sto("b");
nmo("c", "d", "e", "f", "g");
a.b.c.d.e.f.g = "Another happy ending!";
console.log(a.b.c.d.e.f.g); // Our second happy ending was also unhappy...
总之,您在一个函数中定义第二个对象,您可以按顺序在第二个函数中定义任意数量的对象。
我如何以我目前的结构实现这一目标?
【问题讨论】:
-
有什么问题?
-
很难准确说出您的要求。请显示一个前后数据结构,以显示您想要的输入和输出。
标签: javascript nested-loops javascript-objects