【问题标题】:Creating an object in JS在 JS 中创建对象
【发布时间】:2015-10-15 15:45:47
【问题描述】:

我有一个基本遍历类别列表的 for 循环。每个类别(字符串)有 4 个不同的项目,可以是真或假。以下是我的代码的 sn-p:

var i,
    category,
    items,
    categories= {};

    for (i = 0; i < categories.length; i++) {
        category = categories[i];

        items = {};
        items.first = availableItems[i][0] == true;
        items.second = availableItems[i][1] == true;
        items.third = availableItems[i][2] == true;
        items.fourth = availableItems[i][3] == true;

        categories+= { category : items};
    }

我想最终得到一个如下的类别对象结构:

{ category1 : { 
               first : true,
               second : true,
               third : false,
               fourth : true
              },
  category2 : { 
               first : true,
               second : true,
               third : false,
               fourth : false
              },
 category3 : { 
               first : true,
               second : true,
               third : false,
               fourth : false
              }
}

谁能告诉我我做错了什么?

【问题讨论】:

  • categories+= { category : items}; 真的吗?我建议使用categories 作为array,然后使用push 在数组中添加对象。 var categories = []; 和内部for 使用categories.push({ category : items});
  • @Tushar - 我是 JS 新手,所以如果你能给我一个很好的例子
  • @user1809790 在他的评论中有一个例子。
  • 你能解释一下这个问题吗?我不得不删除我的答案,因为我不确定你在问什么
  • @RichardHamilton 所以基本上我需要遍历多个类别,每个类别将有 4 个项目,每个项目可以是真或假。现在,我想得到一个对象,它的结构类似于 { thisIsCategory1 : { first : true, second : false, third : true, Fourth : false }, { thisIsCategory123 : { first : false, second : true, third : false , Fourth : true } } 如您所见,在循环时从类别中检索类别名称

标签: javascript object javascript-objects


【解决方案1】:
var result;
for(var i=0;i<availableItems.length;i++){
   var index = i+1;
   result["category"+index]["first"] = availableItems[i][0] == true
   result["category"+index]["second"] = availableItems[i][1] == true
   result["category"+index]["third"] = availableItems[i][2] == true
   result["category"+index]["fourth"] = availableItems[i][3] == true
}

【讨论】:

    【解决方案2】:
    var category = new Object;
    
    for (i = 0; i < 2; i++) {
        category['category' + (i).toString()] =  (function() {
            var obj = {};
            obj.first = true == true;
            obj.second = false == true;
            return obj;
        })();  
    };
    

    您的代码不起作用,因为 1) 您 cannot get the lenght of an object with the .length property,所以 categories.length 不起作用。和 2) 要将成员添加到对象,您可以使用括号表示法:

    object['member'] = 'string value';
    

    或点符号:

    object.member = 'string value';
    

    但不是这个:categories+= { category : items};

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2015-02-15
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多