gpt4 book ai didi

javascript - 使用JS的数组问题

转载 作者:行者123 更新时间:2023-12-04 00:38:53 25 4
gpt4 key购买 nike

我目前正在使用节点/终端开发一台简单的产品机器,但我遇到了一个问题。我添加了一个数组,其中包含与元素相关的编号 ID。我正在使用 readline 询问用户想要什么产品。

当输入 ID 1 时,它会提供饮料成功的消息。但是当输入 2、3 或 4 时,没有任何反应?

谁能看出我在这里做错了什么,我将不胜感激!

亲切的问候!

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 永远不会被执行,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()将索引作为数字而不是数组返回。

关于javascript - 使用JS的数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34334952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com