我正在尝试使用提示来调用预定义方法来运行计算。当我尝试将提示响应转换为已定义的方法时,它会失败(false),因此在所有情况下都不会计算正确的答案。以下是我的上下文代码:
function PerishableFood(name,lastBuyDate,quantity, expirationDate) {
this.item = name;
this.buyDate = lastBuyDate;
this.quantity = quantity;
this.expireDate = expirationDate;
}
var milk = new PerishableFood('1% Milk','07/05/2017',1, '07/14/2017');
var eggs = new PerishableFood('Cage Free Organic Dozen Eggs', '07/05/2017',2,'07/07/2017');
var bread = new PerishableFood('Honey Wheat Naures Own', '07/05/2017',1,'07/17/2017');
var butter = new PerishableFood('Land O Lakes Real Butter', '07/05/2017',2,'8/30/2017');
然后我计算一个当前日期,我可以在以后用它来确定某些东西是否已过期。这是那部分:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = mm + '/' + dd + '/' + yyyy;
所以此时我现在想要实际使用上述所有代码来实际执行某些操作。我最初拥有它,所以我手动改变了一些事情并且计算得当。但我想使用提示允许我选择我想要计算的项目是否已过期。这是代码,这是我的实际问题,一切都失败了......
var userChoice = prompt("Which would you like the expiration date for? Type: milk, eggs, bread or butter.");
var userChoiceSelected = userChoice + "." + "expireDate";
var expired = function(PerishableFood) {
if(userChoiceSelected<=today) {
// this is what I did before the above which worked but was very manual to change out every time: if(eggs.expireDate<=today) {
return "The " + userChoice + " expired. You need to buy more.";
}
else {
return "You do not need to buy more " + userChoice + ".";
}
}
console.log(expired(PerishableFood));
要查看我的方法是否无效,我写了以下内容:
console.log(userChoiceSelected === milk.expireDate);
当我运行它时,这是错误的。这告诉我,尝试调用userChoiceSelected将不会像我手动输入时那样(参见注释掉的代码)// @(egg.expireDate&lt; =今天),因为这是eggs.expireDate,但显然userChoiceSelected不会变成egg。 expireDate解释了它失败的原因,但我不知道为什么会发生这种情况或如何解决它。谢谢!
答案 0 :(得分:1)
这不是正确的方法。你的变量&#34; userChoiceSelected&#34;是一个字符串,例如&#34; milk.expiredDate&#34;,而不是方法。您应该将所有实例放入Javascript对象中,如下所示:
var myobjects = {
milk: new PerishableFood('1% Milk','07/05/2017',1, '07/14/2017'),
eggs: new PerishableFood('Cage Free Organic Dozen Eggs', '07/05/2017',2,'07/07/2017'),
bread: new PerishableFood('Honey Wheat Naures Own', '07/05/2017',1,'07/17/2017'),
butter: new PerishableFood('Land O Lakes Real Butter', '07/05/2017',2,'8/30/2017')
};
然后您就可以像这样调用userChoice:
userChoiceSelected = myobjetcs[userChoice].expiredDate;
此外,您可以通过将直接过期的方法添加到您的班级来进行演变。因此,您可以拨打myobjects['milk'].isExpired()
,例如。