问题在于:
客户希望购买两台同名电脑,颜色为白色或黑色,总价格低于1600.编写一个JavaScript程序,读取给定的数组var pcs
,并找到他最好的报价。
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
PC,
Collors,
offer = "Offers: " + "\n";
for (var i = 0; i < pcs.length; i++) {
PC = pcs[i];
Collors = Object.keys(PC.color);
if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {
for ( var j = 0; j < Collors.length; j++) {
if ((PC.color.black >= 2) && (PC.color.white >= 2)) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
}
else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[j] + "\n";
}
else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[j] + "\n";
}
}
}
}
console.log(offer);
&#13;
书面代码找到最好的报价,但是有人可以告诉输出中为什么acer
重复自身以及如何修复它?
非常感谢所有人的帮助,
答案 0 :(得分:0)
你循环<StackPanel>
<wpfDemos:FolderPicker Title="Source" FullPath="{Binding Path=Src}" />
<wpfDemos:FolderPicker Title="Destination" FullPath="{Binding Path=Target}"/>
</StackPanel>
。对于Collors
,acer
和black
都有white
。因此,检查>2
的第一条规则与black and white
匹配一次,black
匹配一次。
解决方案是不要遍历white
,而是直接单独检查Collors
和black
:
white
答案 1 :(得分:0)
解决问题以在控制台中获取所需输出的代码。
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
];
for (var i=0; i < pcs.length; i++) {
if((pcs[i].color.black >=2 || pcs[i].color.white >=2) && pcs[i].price *2 <=1600){
//console.log (pcs[i]);
var colors = Object.keys(pcs[i].color),
color = '';
for(var j = 0; j < colors.length; j++){
if ((pcs[i].color.black >= 2 && colors[j] === "black") ||
(pcs[i].color.white >= 2 && colors[j] === "white" )) {
if (color.length > 0) {
color += ' and ' + colors[j];
} else {
color = colors[j];
}
}
}
console.log('Model: ' + pcs[i].model + '\nPrice: ' + pcs[i].price*2 + '\nSpalvos: ' + color);
}
}
&#13;