我有一个名为category
的数组。
var category = ["automobile","Fashion","Music Instruments"]
我需要根据产品将此数组与下面的数组链接起来。
var products = ["LandRover","Guitar","vintage,"Drums","Maserati","Piano"]
最佳答案
我认为您正在谈论类似的事情?...
//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 中显示它的函数(我希望是 void 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);
关于javascript - 如何将一个数组值链接到另一个数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33797737/