我的javascript for-in循环有什么问题

时间:2014-03-22 22:44:01

标签: javascript arrays 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”进行检查时,此部分无效。

3 个答案:

答案 0 :(得分:2)

事实证明你的代码存在很多问题。要使其“正常工作”,您需要解决的关键事项如下:

首先 - 您要求的是“员工编号”,但您的员工结构没有空间。您可以按如下方式修改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>

答案 1 :(得分:0)

在每个单循环中,i中有一个来自stattMembers的元素,而不是它的位置。所以你不能得到0,1,2,但是工作人员[0],工作人员[1],工作人员[2]。你应该考虑一下,在你的情况下,一个简单的for循环可能更好吗?

答案 2 :(得分:0)

问题出在这些方面

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

应该是

if (i === staffNo) {
        cashRegister.applyStaffDiscount(staffMembers[i]);
}
  1. 由于您首先验证员工是否存在索引(否),因此i == staffNo应该是正确的条件。
  2. cashRegister.applyStaffDiscount()需要一个StaffMember实例,以便传递给staffMembers[i]对象。