簡體   English   中英

JavaScript let變量在console.log中顯示為未定義

[英]JavaScript let variable displays as undefined in console.log

到目前為止,我只學習了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

我的代碼執行以下操作:將訂單數量與批量大小進行比較; 如果訂單大小超過該數量,則增加要訂購的手數; 計算最終成本。

我的問題是:如何使整個事情正常工作而無需在函數前聲明order變量?

不要使用let shipment; 使用var shipment; 代替。

在您定義的位置, let防止變量在函數lotCalculator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM