我正在尝试使用数字创建字符串输出。用户输入数字+对应的字符串输出
我的代码似乎关闭了+还可以使用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");
}
更干净的方法是使用地图查找给定数字的日子。例如:
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])
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");
}