到目前为止,我已经学习了JS三个星期,并且在我的一个练习中陷入了某种困境。这是我的代码:
'use strict';
var positions = [
{
title: 'Product_Title_1',
producer: {
name: 'Producer_Name_1',
deferPeriod: 10,
lot: 3
},
price: 10000
},
{
title: 'Product_Title_2',
producer: {
name: 'Producer_Name_2',
deferPeriod: 24,
lot: 14
},
price: 9200
},
{
title: 'Product_Title_3',
producer: {
name: 'Producer_Name_3',
deferPeriod: 5,
lot: 1
},
price: 57000
}
];
console.log('Task 1:');
console.log();
let order = 10; //declaring it here solves the problem in a way, but it is not the way it should work
let shipment;
function lotCalculator (positions, order) {
return shipment = {
lots: Math.ceil(order / positions.producer.lot),
total: Math.ceil(order / positions.producer.lot) * positions.producer.lot * positions.price
};
}
let result1 = lotCalculator (positions[1], 15);
console.log(result1);
console.log();
console.log(`Order for Product_Title_2: ${order} pcs, order lots: ${shipment.lots}, final cost ${shipment.total} Q`); //order returns undefined
我的代码执行以下操作:它按顺序比较批次的件数;如果订单大小超过订单,则增加订单数量;计算最终费用。
我的问题是:如果不在函数之前声明订单变量,我怎么能让整个事情正常工作?
答案 0 :(得分:0)
请勿使用let shipment;
代替var shipment;
。
您定义的位置let
会阻止变量在函数lotCalculator