![](/img/trans.png)
[英]How would I rewrite this code using a for loop instead of using the […Array].map() method?
[英]how to write for loop code with JavaScript Array map Method
這是我在JavaScript中用for循環編寫的代碼
var data = [{id: "1",LinkTitle: "a1", SubCategories: [{ id: "12",
LinkTitle: "b1",
SubCategories: []
}]
},
{
id: "2",
LinkTitle: "l1",
SubCategories: [
{
id: "21",
LinkTitle: "l2",
SubCategories: []
},
{
id: "22",
LinkTitle: "aa",
SubCategories: []
}
]
}
];
var cat = [];
var x = ["l1", "l2"];
for (let i = 0; i < x.length; i++) {
cat[i] = data.find(e => e.LinkTitle == x[i]);
if (cat[i]) {
data = cat[i].SubCategories;
}
}
有什么辦法可以從此代碼中刪除for循環,並用數組映射方法替換它
有可能 ,只需將找到的項目保存在變量中,然后在回調的末尾將其返回:
var data = [{ id: "1", LinkTitle: "a1", SubCategories: [{ id: "12", LinkTitle: "b1", SubCategories: [] }] }, { id: "2", LinkTitle: "l1", SubCategories: [{ id: "21", LinkTitle: "l2", SubCategories: [] }, { id: "22", LinkTitle: "aa", SubCategories: [] } ] } ]; var x = ["l1", "l2"]; const cat = x.map((linkTitleToFind) => { const result = data.find(e => e.LinkTitle == linkTitleToFind); if (result) { data = result.SubCategories; } return result; }); console.log(cat);
也就是說, .map
重新分配很奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.