接受提示号码输入+打印字符串

问题描述 投票:0回答:2

我正在尝试使用数字创建字符串输出。用户输入数字+对应的字符串输出

我的代码似乎关闭了+还可以使用for / while循环使之更整洁吗?

//Single input
let num = prompt("Please enter a number");


//Comparing if
if (num === 1)
{
   console.log("Mon");
} 
else if (num === 2)
{
  console.log ("Tue");
}
else if (num === 3)
{
  console.log ("Wedn");
}
else if (num === 4)
{
  console.log ("Thurs");
}
else if (num === 5)
{
  console.log ("Frid");
}
else if (num === 6)
{
  console.log ("Satu");
}
else if (num === 7)
{
  console.log ("Sund");
}
string for-loop prompt
2个回答
0
投票

更干净的方法是使用地图查找给定数字的日子。例如:

let days = {
  1: "Mon",
  2: "Tue",
  3: "Wed",
  4: "Thur",
  5: "Fri",
  6: "Sat",
  7: "Sun",
}


let num = prompt("Please enter a number");
console.log(days[num])

0
投票

let num =提示(“请输入一个数字”);返回一个字符串,而不是数字,您必须将结果转换为数字。

一种方法:

let num = +prompt("Please enter a number"); // note the plus sign before prompt

let num = parseInt(prompt("Please enter a number"));

//Single input
let num = +prompt("Please enter a number");


//Comparing if
if (num === 1)
{
   console.log("Mon");
} 
else if (num === 2)
{
  console.log ("Tue");
}
else if (num === 3)
{
  console.log ("Wedn");
}
else if (num === 4)
{
  console.log ("Thurs");
}
else if (num === 5)
{
  console.log ("Frid");
}
else if (num === 6)
{
  console.log ("Satu");
}
else if (num === 7)
{
  console.log ("Sund");
}

关于使整洁?

const daysOfTheWeek = ["Mon", "Tue", "Wedn", "Thurs", "Frid", "Satu", "Sund"];
const day = +prompt("Please enter a number");

if(day > 0 && day <= daysOfTheWeek.length){
    console.log(daysOfTheWeek[day - 1]);
} else {
    console.log("No such day");
}
© www.soinside.com 2019 - 2024. All rights reserved.