簡體   English   中英

循環項目(列表)的變量,每個項目也是一個帶項目的變量(列表)

[英]Loop items (list) of a variable, each item is also a variable with items (list)

我的代碼是這樣的:

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”)。 知道我做錯了什么嗎?

您還可以像這樣定義變量:

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

var allcategories = [category1, category2, category3];

在這里定義3個數組,然后定義包含它們的“保持”數組。

最簡單的方法是將變量名稱作為對象的屬性鍵來代替:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM