我试图采取一个数组列表,并将类似对象组合到一个新的数组,但我一直未达到我想要做的。注意:我正在使用jQuery $.each()
以及其他可能会使这种“更慢”的东西,但我只是希望逻辑先工作。所以,短篇小说:我有一些用户可以选择的项目,当他们选择一个项目时,我把它放到一个名为materials
的数组列表中。该数组列表包含用户选择的所有内容以及该项目的所有子项。这里和示例:如果用户选择“木路障”和“睡袋”这将增加materials
阵列输出像这样:现在Javascript比较和组合项目在一个新的数组
["woodBarricade|1", "wood|30", "sleepingBag|1", "cloth|15"];
,如果用户在“木板”补充说,该阵列变成:
["woodBarricade|1", "wood|30", "sleepingBag|1", "cloth|15", "woodPlanks|1", "wood|10"];
我现在想要做的是结合像选择。在上面的例子中,它要结合这两个“木”的项目和新的阵列应该说:
["woodBarricade|1", "wood|40", "sleepingBag|1", "cloth|15", "woodPlanks|1"];
这是我到目前为止有:
function calculateMaterials(){ //Start the function
var conMaterialList = []; //Empty the list every time.
$.each(materials, function(a){ //for each material in the list
var materialName = materials[a].split("|")[0]; //Get it's name
var materialCount = parseInt(materials[a].split("|")[1]); //And the quantity
if(conMaterialList == ""){ //Then if the conMaterialList is empty
conMaterialList.push(materialName+"|"+materialCount); //Add the first material
} else { // If the conMaterialList is NOT empty
$.each(conMaterialList, function(b){ //iterate through the list
var materialNameComp = conMaterialList[b].split("|")[0]; //Get the name
var materialCountComp = parseInt(conMaterialList[b].split("|")[1]); //Get the quantity
if(materialName == materialNameComp){ // If the item from 'materials' matches an item from 'conMaterialList'
conMaterialList.splice(b, 1, materialNameComp +"|"+ parseInt(materialCount + materialCountComp)); //combine that material
} else { // If it does not match
conMaterialList.push(materialName +"|"+ materialCount); //push that material into the array
}
});
}
});
console.log(conMaterialList); //Show me the conMaterialList
}
这种近乎工作。如果我是用上面的例子来试试这个(选择木路障,睡袋和木板),我会得到这样的输出:
["woodBarricade|1", "wood|40", "sleepingBag|1", "sleepingBag|1", "cloth|15", "cloth|15", "cloth|15", "cloth|15", "woodPlanks|1", "woodPlanks|1", "woodPlanks|1", "woodPlanks|1", "woodPlanks|1", "woodPlanks|1", "woodPlanks|1", "woodPlanks|1", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10", "wood|10"]
正如你可以看到,第一个“木”有一个量40.这在技术上确实将两个木桩加在一起。但那之后发生的事情目前对我来说是个谜。
我已经被告知我正在做这个尽可能最慢的方法,但我希望逻辑在我加速之前先工作。
有关如何组合项目并制作简单清单的任何想法?
而不是数组,你可以使用对象。 '{ “woodBarricade”:1, “wood”:10, }' 现在增加数据变得很容易。 – palanik
伟大的一点。每个已经存在的对象都有一个实际的对象。 woodBarricade是我自己拥有“材料”构建的对象。我会做新的东西吗? – ntgCleaner
仍然在寻找解决这个问题的答案,但我找出下一个,FYI – ntgCleaner