javascript 如何在循环中创建动态对象?

piwo6bdm  于 2023-10-14  发布在  Java
关注(0)|答案(6)|浏览(102)

基本上,我想在JavaScript中创建一个包含许多对象的大对象。例如:

var objects = {}
for (x)
objects.x = {name: etc}

有什么想法吗?

ars1skjm

ars1skjm1#

var objects = {};

for (var x = 0; x < 100; x++) {
  objects[x] = {name: etc};
}
fnvucqvd

fnvucqvd2#

实际实现

用100个其他对象填充容器对象。

<script>
var container = { }; // main object

// add 100 sub-object values
for(i = 0; i < 100; ++i) {
 container['prop'+i ]  /*property name or key of choice*/
         = { 'a':'something', 
             'b':'somethingelse', 
             'c': 2 * i
           }; 
}

测试结果-显示和显示对象.

for(var p in container) {
 var innerObj = container[p];
 document.write('<div>container.' + p + ':' + innerObj + '</div>');
 // write out properties of inner object
 document.write('<div> .a: ' + innerObj['a'] + '</div>');
 document.write('<div> .b: ' + innerObj['b'] + '</div>');
 document.write('<div> .c: ' + innerObj['c'] + '</div>');
}
</script>

输出就像

container.prop0:[object Object]
.a: something
.b: somethingelse
.c: 0
container.prop1:[object Object]
.a: something
.b: somethingelse
.c: 2
container.prop2:[object Object]
.a: something
.b: somethingelse
.c: 4

等等

9rnv2umw

9rnv2umw3#

使用object[propertyname]与使用object.propertyname相同,因此我们可以动态创建object[propertyname]的对象键。
例如:

var fruits = ["Apple", "Orange", "Banana","Grapes"];
var colors = ["red", "Orange", "yellow","blue"];
var newObj = {};
for (var i = 0; i < fruits.length; i++) {
  newObj[fruits[i]] = colors[i];
}
console.log(newObj);
wkyowqbh

wkyowqbh4#

试试这个

var objects = new Array();
var howmany = 10;

for (var i = 0; i < howmany; i++)
{
    objects[i] = new Object();

}
olmpazwi

olmpazwi5#

//On Nested Obj like that
var playersCount = {
    "Players" : {}
}

var exempleCount = 5;

for(i=0; i <= exempleCount;i++){
    var BadID = Math.floor(Math.random() * 10000);
  
        playersCount.Players["Player_"+i] = {
            "id":BadID, 
            "xPos":0, 
            "yPos":0, 
            "zPos":0
        };
    }
  console.log(playersCount);
svujldwt

svujldwt6#

一种可重用的动态对象生成方法

const text = ["Cherries", "Strawberry", "Banana"];
const emoji = ["🍒", "🍓", "🍌"];

const createDynamicObj = (keys, values) => {
  if(!keys || !values) return
  let newObj = {};

  for (let i = 0; i < keys.length; i++) {
    newObj[keys[i]] = values[i];
  }
  return newObj
}

console.log(
  createDynamicObj(emoji, text)
)

相关问题