问题是重复的,对不起。
答案 0 :(得分:5)
您的嵌套if
永远不会被执行,index
不能同时为1和3。我建议您改用switch
,它基本上就是您要做的事情:
var productPurchase = readlineSync.question('Would you like to purchase a product? ');
if (productPurchase == "yes") {
index = readlineSync.keyInSelect(products, 'What product would you like?');
switch (index) {
case 1 :
console.log('Thank you, your Drink' + ' has now been dispensed.');
break;
case 2 :
console.log('Thank you, your Crisps' + ' has now been dispensed.');
break;
case 3 :
console.log('Thank you, your Chocolate' + ' has now been dispensed.');
break;
case 4 :
console.log('Thank you, your Candy' + ' has now been dispensed.');
break;
default :
console.log('something went wrong');
break;
}
}
注意:纠正了index
的错误用法。 keyInSelect()
将索引作为数字返回,而不是数组。
答案 1 :(得分:3)
试试这个:
var readlineSync = require('readline-sync'),
products = [];
products[1] = "Drink";
products[2] = "Crisps";
products[3] = "Chocolate";
products[4] = "Candy";
var productPurchase = readlineSync.question('Would you like to purchase a product? ');
if (productPurchase == "yes") {
index = readlineSync.keyInSelect(products, 'What product would you like?');
if (index == [1])
console.log('Thank you, your Drink' + ' has now been dispensed.');
else if (index == [2])
console.log('Thank you, your Crisps' + ' has now been dispensed.');
else if (index == [3])
console.log('Thank you, your Chocolate' + ' has now been dispensed.');
else if (index == [4])
console.log('Thank you, your Candy' + ' has now been dispensed.');
}
答案 2 :(得分:2)
您正在嵌套if
语句。将它们设置在同一级别。或者,也可以使用if else
:
if (index == 1) {
console.log('Thank you, your Drink' + ' has now been dispensed.');
}
else if (index == 2) {
console.log('Thank you, your Crisps' + ' has now been dispensed.');
}
else if (index == 3) {
console.log('Thank you, your Chocolate' + ' has now been dispensed.');
}
else if (index == 4) {
console.log('Thank you, your Candy' + ' has now been dispensed.');
}
答案 3 :(得分:2)
你的花括号搞砸了。你有这样的一个像这样:
if(){
if(){
if(){
if(){
}
}
}
}
尝试将代码更改为:
var readlineSync = require('readline-sync'),
products = [];
products[1] = "Drink";
products[2] = "Crisps";
products[3] = "Chocolate";
products[4] = "Candy";
var productPurchase = readlineSync.question('Would you like to purchase a product? ');
if (productPurchase == "yes") {
index = readlineSync.keyInSelect(products, 'What product would you like?');
if (index == 1) {
console.log('Thank you, your Drink' + ' has now been dispensed.');
}
if (index == 2) {
console.log('Thank you, your Crisps' + ' has now been dispensed.');
}
if (index == 3) {
console.log('Thank you, your Chocolate' + ' has now been dispensed.');
}
if (index == 4) {
console.log('Thank you, your Candy' + ' has now been dispensed.');
}
}
使用正确的缩进有助于避免此类问题。如果您的代码编写得更干净,您可能会立即发现问题。
注意:您可能希望将这些if
语句更改为switch
。这种情况可能是最好的。