我有一个名为category
的数组。
var category = ["automobile","Fashion","Music Instruments"]
我需要根据产品将此数组与以下数组相关联。
var products = ["LandRover","Guitar","vintage,"Drums","Maserati","Piano"]
答案 0 :(得分:1)
我觉得你在谈论这样的事情?...
//variables predefined
var category = ["Automobile","Fashion","Music Instruments"]
var products = ["LandRover","Guitar","vintage","Drums","Maserati","Piano"]
//create a object categories where later we will add our products!
var categories = { };
//add values(category & products)
categories[ category[0] ] = [ products[0] , products[4] ]; //Automobile
categories[ category[1] ] = [ products[2] ]; //Fashion
categories[ category[2] ] = [ products[1] , products[3] ,products[5] ]; //Music Instrument
所以现在如果你想显示一些'汽车'的价值,只需:
//METHOD1
categories['automobile']
//METHOD2
categories[ category[0] ] //category[0]->automobile
你得到的是包含所有类别产品的阵列,所以你只需要选择你想要的产品。 在这里你可以看到你在控制台中得到了什么。
用于在某些HTML中显示它的函数(我希望无效的html)
function showObjectOnHTML( obj ){
for (var key in categories) { //check categories of thethe object
if (categories.hasOwnProperty(key)) {
var CATEGORIES = key;
var SPAN = document.createElement('SPAN');
SPAN.setAttribute('style','font-weight:bold; font-size: 20px; margin-left: 5px; display:block;');
SPAN.appendChild( document.createTextNode( CATEGORIES ) );
document.body.appendChild(SPAN);
var PRODUCTS = categories[key];
for( var i=0; i<PRODUCTS.length; i++){
var SPAN = document.createElement('SPAN');
SPAN.setAttribute('style','margin-left: 15px;font-size: 20px; display:block;');
SPAN.appendChild( document.createTextNode( PRODUCTS[i] ) );
document.body.appendChild(SPAN);
}
}
}
}
要显示它,只需输入:
showObjectOnHTML(categories);
答案 1 :(得分:0)
我认为你需要的是一个对象(在java中像“hashmap”一样使用):
//set examples
var category = {
automobile: [],
fashion: [],
musicInstuments: ["Piano"]
};
category["automobile"] = category["automobile"].concat(["LandRover", "Maserati"]);
category.fashion.push("Vintage");
//get examples
for(var key in category){
category[key].forEach(function(item){
console.log(item);
});
}
console.log(category.automobile[0]);
使用对象还可以为您提供对所查找类别的持续访问时间(而不是迭代n个项目来查找它)
答案 2 :(得分:0)
也许你使用的是对象而不仅仅是列表?
var categories = [
{
name: "Automobile",
products: ["LandRover", "Maserati"]
},
{
name: "Fashion",
products: ["Vintage"]
},
{
name: "Music Instruments",
products: ["Guitar", "Drums", "Piano"]
}
]
另外,就像有人评论过,你想要完成什么?
修改强>
This JSFiddle显示了一种使用AngularJS列出每个类别中的产品的方法。