- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 javascript 的新手,目前正在编写一个在终端中运行的基本文件。它的大部分都在工作。它允许用户添加信用/删除信用并检查他们的信用。最后一部分是允许他们购买产品并将该金额从他们的整体信用中扣除。
我遇到的问题是,虽然它确实显示购买商品时金额已被删除。当返回菜单并在之后检查剩余信用时,它又回到了原来的数额。
我尝试使用下面的代码来保存信用(即使在检查可用信用后它也会这样做):
credit -= readlineSync.keyInSelect(products, 'What product would you like?');
但由于该数组使用了用户输入的数字,因此它会从总积分而不是实际价格中删除该数字。因此,例如,如果用户选择选项 4,它会从积分中删除 4,而实际上糖果是 £3。
如果我能提供任何帮助,我们将不胜感激,因为我已经花了很长时间没有找到解决方案。
最佳答案
我稍微清理了您的代码并修复了您观察到的问题:
var readlineSync = require('readline-sync');
var credit = 0;
var index;
var menu = [
'Purchase a product',
'View your credit',
'Add credit',
'Retrieve a refund',
'Quit!'
];
var products = [
'Drink',
'Crisps',
'Chocolate',
'Candy'
];
var prices = [1, 1, 2, 3];
var productList = products.map(function(product, i) {
return product + ': £' + prices[i];
});
do {
index = readlineSync.keyInSelect(menu, 'Please choose your option');
if (index == 1) {
console.log('The total amount of credit you have is: £%d', credit);
}
if (index == 2) {
credit += readlineSync.questionInt('How much credit would you to purchase? ');
console.log('The total amount of credit you have is: £%d', credit);
}
if (index == 3) {
credit -= readlineSync.questionInt('How much credit would you like to remove? ');
console.log('This credit has now been removed, your total available credit is: £%d', credit);
}
if (index == 0) {
index = readlineSync.keyInSelect(productList, 'What product would you like?');
if (index >= 0 && index < products.length) {
credit -= prices[index];
console.log('Thank you, your %s has now been dispensed. Your total credit is now £%d', products[index], credit);
}
continue;
}
} while(index != 4);
这里有几个关键的事情,我将解决我看到的一些您没有指出的问题:
您从未声明过 index
。虽然这在非严格模式下被认为是有效的,但这是一种不好的做法,因为分配未声明的变量会将其暴露给全局范围。
您没有一组价格
,因此您当然会遇到问题,无法确定要从您的信用中减去多少值(value)。我冒昧地为您添加了那个数组。
细目如下:
var productList = products.map(function(product, i) {
return product + ': £' + prices[i];
});
此函数遍历 products
中的值,对于每个值 product
和每个索引 i
,它返回一个新的字符串,格式如下product: £price
,将其存储到数组 productList
的相应索引中。
我更改了您的 console.log
语句以使用内联格式使其更清晰。 %s
表示放一个字符串,%d
表示放一个整数。然后使用以下参数来填充这些格式说明符。
我在您的最后一个 if
block 中添加了一个 continue
语句,以便提前返回循环。这是因为 index
被您选择的产品覆盖,因此它不再反射(reflect)原始菜单选择。
如果您对我的反馈有任何疑问,请随时发表评论。
关于javascript - 整数不保存在循环/部分工作的 JS 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358737/
我是一名优秀的程序员,十分优秀!