簡體   English   中英

我的javascript for-in循環有什么問題

[英]What is wrong with my javascript for-in loop

<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
//Definition of staff members (class)
function StaffMember(name,discountPercent){
    this.name = name;
    this.discountPercent = discountPercent;
}
//Creation of staff members (object)
var s121 = new StaffMember("Sally",5);
var b122 = new StaffMember("Bob",10);
var d123 = new StaffMember("Dave",20);
staffMembers = [s121,b122,d123];
//Creation of cash register (object)
var cashRegister = {
    total:0,
    lastTransactionAmount: 0,
    //Add to the total (method)
    add: function(itemCost){
        this.total += (itemCost || 0);
        this.lastTransactionAmount = itemCost;
    },
    //Retreive the value of an item (method)
    scan: function(item,quantity){
        switch (item){
        case "eggs": this.add(0.98 * quantity); break;
        case "milk": this.add(1.23 * quantity); break;
        case "magazine": this.add(4.99 * quantity); break;
        case "chocolate": this.add(0.45 * quantity); break;
        }
        return true;
    },
    //Void the last item (method)
    voidLastTransaction : function(){
        this.total -= this.lastTransactionAmount;
        this.lastTransactionAmount = 0;
    },
    //Apply a staff discount to the total (method)
    applyStaffDiscount: function(employee) {
        this.total -= this.total * (employee.discountPercent / 100);
    }

};
//Ask for number of items
do {
  var numOfItems = prompt("How many items do you have?");
  document.body.innerHTML = numOfItems;
  if (isNaN(numOfItems)) {
      i=0;
    } else {
      i=1;
    }
} while (i===0);
//Ask for item and qty of item
var items = [];
var qtys = [];
for(var i=0;i<numOfItems;i++) {
  var j=0;
  do {
  items[i] = prompt("What are you buying? (eggs, milk, magazine, chocolate)");
  switch (items[i]) {
    case "eggs" :;
    case "milk" :;
    case "magazine" :;
    case "chocolate" : j=1; document.body.innerHTML = items[i]; break;
    default : document.body.innerHTML = 'Item not reconized, please re-enter...'
; break;}
  } while (j===0);
  do {
    qtys[i] = prompt("How many " + items[i] + " are you buying?");
    document.body.innerHTML = qtys[i];
    if (isNaN(qtys[i])) {
      j=1;
    } else {
      j=0;
    }
  } while (j===1);
  //Add to the sub-total
  cashRegister.scan(items[i],qtys[i])
}
//Find out if it's a staff member & if so apply a discount
var customer;
var staffNo;
do {
  customer = prompt("Please enter customer name or type 'staff'.");
  document.body.innerHTML = customer;
  if (customer === 'staff') {
    staffNo = prompt("Please enter your staff number");
    for (i in staffMembers) {
      if (staffMembers[i] === staffNo) {
        cashRegister.applyStaffDiscount(staffNo);
      } else {
        document.body.innerHTML = "Staff number not found";
      };
    }
  }
  i=1;
} while (i=0);
// Show the total bill
if (customer !== 'staff') {
  document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
  +' Thank you for visiting ' +customer;
} else {
  document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
  +' Thank you for visiting ' +staffNo;
};

</script>
</body>
</html> 

我的代碼似乎有什么問題,它的工作原理但不適用員工折扣,我覺得錯誤是存在的;

    for (i in staffMembers) {
      if (staffMembers[i] === staffNo) {
        cashRegister.applyStaffDiscount(staffNo);
      } else {
        document.body.innerHTML = "Staff number not found";
      };
    }

任何人都可以幫助發現錯誤,我一直在學習CodeAcademy,但已經進一步檢查輸入的數據。 但我似乎無法理解為什么這部分在通過' http://www.compileonline.com/try_javascript_online.php '檢查時不能正常工作。

事實證明你的代碼存在很多問題。 要使其“正常工作”,您需要修復的關鍵事項如下:

首先 - 您要求的是“員工編號”,但您的員工結構沒有空間。 您可以按如下方式修改StaffMember

//Definition of staff members (class)
function StaffMember(name, number, discountPercent){
    this.name = name;
    this.number = number;
    this.discountPercent = discountPercent;
}
//Creation of staff members (object)
var s121 = new StaffMember("Sally","s121",5);
var b122 = new StaffMember("Bob","b122",10);
var d123 = new StaffMember("Dave","d123",20);
staffMembers = [s121,b122,d123];

現在你有一個“唯一標識符” - 我決定給員工提供與變量名相同的號碼,但這不是必需的。

接下來,讓我們看一下你所擁有的循環:將其更改為

do {
  customer = prompt("Please enter customer name or type 'staff'.");
  document.body.innerHTML = customer;
  if (customer === 'staff') {
    staffNo = prompt("Please enter your staff number:");
    for (i in staffMembers) {
      if (staffMembers[i].number === staffNo) {  // <<<<< change the comparison
        cashRegister.applyStaffDiscount(staffMembers[i]);  // <<<<< call applyStaffDiscount with the right parameter: the object, not the staff number
      } else {
        document.body.innerHTML = "Staff number not found";
      };
    }
  }
  i=1;  // <<<<< I really don't understand why you have this do loop at all.
} while (i == 0); // <<<<< presumably you meant "while(i == 0)"? You had "while (i=0)"

你可以做很多很多事情來改善它 - 但至少這會讓你開始。 完整的“工作”代碼(我可能做了其他編輯,我忘了指出 - 但下面是直接從我的工作空間復制,“工作” - 雖然相當片狀):

<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
//Definition of staff members (class)
function StaffMember(name, number, discountPercent){
    this.name = name;
    this.number = number;
    this.discountPercent = discountPercent;
}
//Creation of staff members (object)
var s121 = new StaffMember("Sally","s121",5);
var b122 = new StaffMember("Bob","b122",10);
var d123 = new StaffMember("Dave","d123",20);
staffMembers = [s121,b122,d123];
//Creation of cash register (object)
var cashRegister = {
    total:0,
    lastTransactionAmount: 0,
    //Add to the total (method)
    add: function(itemCost){
        this.total += (itemCost || 0);
        this.lastTransactionAmount = itemCost;
    },
    //Retreive the value of an item (method)
    scan: function(item,quantity){
        switch (item){
        case "eggs": this.add(0.98 * quantity); break;
        case "milk": this.add(1.23 * quantity); break;
        case "magazine": this.add(4.99 * quantity); break;
        case "chocolate": this.add(0.45 * quantity); break;
        }
        return true;
    },
    //Void the last item (method)
    voidLastTransaction : function(){
        this.total -= this.lastTransactionAmount;
        this.lastTransactionAmount = 0;
    },
    //Apply a staff discount to the total (method)
    applyStaffDiscount: function(employee) {
        this.total -= this.total * (employee.discountPercent / 100);
    }

};
//Ask for number of items
do {
  var numOfItems = prompt("How many items do you have?");
  document.body.innerHTML = numOfItems;
  if (isNaN(numOfItems)) {
      i=0;
    } else {
      i=1;
    }
} while (i===0);
//Ask for item and qty of item
var items = [];
var qtys = [];
for(var i=0;i<numOfItems;i++) {
  var j=0;
  do {
  items[i] = prompt("What are you buying? (eggs, milk, magazine, chocolate)");
  switch (items[i]) {
    case "eggs" :;
    case "milk" :;
    case "magazine" :;
    case "chocolate" : j=1; document.body.innerHTML = items[i]; break;
    default : document.body.innerHTML = 'Item not reconized, please re-enter...'
; break;}
  } while (j===0);
  do {
    qtys[i] = prompt("How many " + items[i] + " are you buying?");
    document.body.innerHTML = qtys[i];
    if (isNaN(qtys[i])) {
      j=1;
    } else {
      j=0;
    }
  } while (j===1);
  //Add to the sub-total
  cashRegister.scan(items[i],qtys[i])
}
//Find out if it's a staff member & if so apply a discount
var customer;
var staffNo;
do {
  customer = prompt("Please enter customer name or type 'staff'.");
  document.body.innerHTML = customer;
  if (customer === 'staff') {
    staffNo = prompt("Please enter your number:");
    for (i in staffMembers) {
      if (staffMembers[i].number === staffNo) {
        cashRegister.applyStaffDiscount(staffMembers[i]);
      } else {
        document.body.innerHTML = "Staff number not found";
      };
    }
  }
  i=1;
} while (i=0);
// Show the total bill
if (customer !== 'staff') {
  document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
  +'<br> Thank you for visiting ' + customer;
} else {
  document.body.innerHTML = 'Your bill is £'+cashRegister.total.toFixed(2)
  +'<br> Thank you for visiting staff member ' +staffNo;
};

</script>
</body>
</html>

在每個單循環中,有一個來自i中的stattMembers的元素,而不是它的位置。 因此,你不會得到0,1,2但是會員[0],工作人員[1],工作人員[2]。 你應該考慮一下,也許一個簡單的for循環在你的情況下更好?

問題在於這些問題

if (staffMembers[i] === staffNo) {
        cashRegister.applyStaffDiscount(staffNo);
} 

應該是的

if (i === staffNo) {
        cashRegister.applyStaffDiscount(staffMembers[i]);
}
  1. 由於您首先驗證了員工的索引(否)是否存在,因此i == staffNo應該是正確的條件。
  2. cashRegister.applyStaffDiscount()期望一個StaffMember的實例,所以傳遞給staffMembers[i]對象就可以了。

暫無
暫無

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

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