【问题标题】:Loop items (list) of a variable, each item is also a variable with items (list)循环items(list)的一个变量,每个item也是一个带有items(list)的变量
【发布时间】:2018-11-10 16:43:29
【问题描述】:

我的代码是这样的:

var allcategories = ["category1", "category2", "category3"];
var category1 = ["item1", "item2", "item3"];
var category2 = ["item4", "item5", "item6", "item7", "item8"];
var category3 = ["item9", "item10"];

for (let currentcategory of allcategories) {
    for (let categoryitem of currentcategory) {
        console.log (currentcategory, categoryitem);
    };
};

“allcategories”变量中列出的每个项目也是一个包含已保存项目的变量。 我的目标是获取变量“category1, category2 category3 ...”的值,但这仅返回变量的第一个字母(“C”)。 知道我做错了什么吗?

【问题讨论】:

  • allcategories的字符串常量和下面3行的数组对象不一样

标签: javascript arrays object for-loop


【解决方案1】:

你也可以像这样定义你的变量:

var category1 = ["item1", "item2", "item3"];
var category2 = ["item4", "item5", "item6", "item7", "item8"];
var category3 = ["item9", "item10"];

var allcategories = [category1, category2, category3];

在这里定义 3 个数组,然后定义一个包含它们的“持有”数组。

【讨论】:

    【解决方案2】:

    最简单的方法是将变量名称作为对象中的属性键:

    const allcategories = ["category1", "category2", "category3"];
    
    const categoryObj = {
      category1: ["item1", "item2", "item3"],
      category2: ["item4", "item5", "item6", "item7", "item8"],
      category3: ["item9", "item10"]
    }
    
    for (let currentcategory of allcategories) {
      for (let categoryitem of categoryObj[currentcategory]) {
        console.log(currentcategory, categoryitem);
      };
    };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 2014-08-03
      • 2021-12-28
      • 2018-10-13
      • 1970-01-01
      • 2014-10-28
      • 2011-12-02
      相关资源
      最近更新 更多