我试图遍历以下数组,但未成功
我的方法正确吗? 我对我的代码做了很多更改,可能不是原来的
我的尝试:
shinyApp(
ui = fluidPage(
selectInput("selection",
"Select Something:",
list("Boring" = " ",
"Positive" = c("Cool", "Groovy", "Rad"),
"Basic" = " ",
"Taco" = c("Bell", "Hell")),
selected = "Groovy"
),
textOutput("result")
),
server = function(input, output) {
output$result <- renderText({
paste("You chose", input$selection)
})
}
)
数组:
var gender = ["men", "women"];
var category = [
"topwear",
"bottomwear",
"indianwear",
"westernwear",
];
for (var i = 0; i < categories.length; i++) {
for (var g = 0; g < gender.length; g++) {
for (j = 0; j < categories[i][gender[g]].length; j++) {
for (var c = 0; c < category.length; c++) {
console.log("=======category========", category[c]);
for (k = 0; k < categories[i][gender[g]][j][category[c]].length; k++) {
console.log(categories[i][gender[g]][j][category[c]][k]);
}
}
}
}
}
我需要获取数组中的名称。 因为我需要在内部编写的代码中使用它 最循环。
预先感谢
答案 0 :(得分:1)
您的代码希望数组中的每个对象都具有men
和women
属性。但是这些属性位于单独的数组元素中。因此,您需要在尝试遍历其元素之前检查该属性是否存在。否则,您将尝试获取未定义属性的长度。
类似地,men
或women
数组中的每个对象只有一个属性,而不是category
数组中的所有属性。
如果将变量分配给数组的当前元素,则循环将容易得多,因此不需要带有很多索引的长表达式,例如categories[i][gender[g]][j][category[c]][k]
。并且使用forEach()
可以简化这一过程。
var gender = ["men", "women"];
var category = [
"topwear",
"bottomwear",
"indianwear",
"westernwear",
];
var categories = [{
men: [{
topwear: [
"men-topwear",
"men-tshirts",
"men-casual-shirts",
"men-formal-shirts",
"men-sweatshirts",
"men-sweaters",
"men-jackets",
"men-blazers",
"men-suits",
"rain-jacket",
],
},
{
bottomwear: [
"men-jeans",
"men-casual-trousers",
"men-formal-trousers",
"mens-shorts",
"men-trackpants",
"men-innerwear",
"men-briefs-and-trunks",
"men-boxers",
"men-innerwear-vests",
"men-nightwear",
"men-thermals",
],
},
],
},
{
women: [{
indianwear: [
"women-kurtas-kurtis-suits",
"ethnic-tops",
"ethnic-wear-dresses-menu",
"women-ethnic-bottomwear?f=categories%3AChuridar%2CLeggings%2CSalwar",
"skirts-palazzos",
"saree",
"dress-material",
"lehenga-choli",
"dupatta-shawl",
"women-ethnic-wear-jackets",
"dresses?f=Gender%3Amen%20women%2Cwomen",
"jumpsuits?f=Gender%3Amen%20women%2Cwomen",
],
},
{
westernwear: [
"women-shirts-tops-tees",
"women-jeans-jeggings",
"women-trousers",
"women-shorts-skirts",
"women-shrugs",
"women-sweaters-sweatshirts",
"women-jackets-coats",
"women-blazers-waistcoats",
],
},
],
},
];
categories.forEach(catItem =>
gender.forEach(genItem => {
if (catItem[genItem]) {
category.forEach(cat => {
console.log("=======category========", cat);
catItem[genItem].forEach(i => {
if (i[cat]) {
i[cat].forEach(x => console.log(x));
}
});
});
}
})
);