您好我是编码的新手,我想尝试一下我学到了多少(不是那么多) 所以我做到了:
var Name = prompt('What is your name?')
var Name
var Age = prompt('What is your age?')
var Age
const RealAge = 2018 - Age
if (Name && RealAge) {
console.log("Hello " + Name + " you were born in " + RealAge + ' ...')
} else if (typeof Name == 'undefined') {
console.log("Please insert your name")
} else if (typeof Age == 'undefined' ) {
console.log("Please insert your age")
}
我想知道怎么制作console.log如果你把第一个提示留空,请说“请插入你的名字”,如果第二个提示留空,请说“请插入你的年龄”。
我很抱歉,如果这是一个愚蠢的问题,但我刚刚开始2天前,我将非常感谢你的帮助:)
答案 0 :(得分:4)
if (Name && RealAge) {
console.log("Hello " + Name + " you were born in " + RealAge + ' ...')
} else if (!Name) {
console.log("Please insert your name")
} else if (!Age) {
console.log("Please insert your age")
}
如果值为falsy(未定义,null,空字符串), !Name
将计算为true。
此外,正如Frederico所提到的,最好在进行任何计算之前检查这些值:
var Name = prompt('What is your name?')
var Name
var Age = prompt('What is your age?')
var Age
if (!Name) {
console.log("Please insert your name")
} else if (!Age) {
console.log("Please insert your age")
} else {
const RealAge = 2018 - +Age;
console.log("Hello " + Name + " you were born in " + RealAge + ' ...')
}
如果你需要知道什么时候都没有输入:
var Name = prompt('What is your name?')
var Name
var Age = prompt('What is your age?')
var Age
if (!Name) {
if (!Age) {
console.log("Please insert your name and age")
}
else {
console.log("Please insert your name")
}
} else if (!Age) {
console.log("Please insert your age")
} else {
const RealAge = 2018 - +Age;
console.log("Hello " + Name + " you were born in " + RealAge + ' ...')
}
答案 1 :(得分:2)
您不会一次又一次地声明变量。此外,如果用户未在提示中输入任何内容,则其值为""
且未定义。所以请查看=== ""
。
var Name = prompt('What is your name?');
var Age = prompt('What is your age?');
const RealAge = 2018 - +Age;
if (Name && RealAge) {
console.log("Hello " + Name + " you were born in " + RealAge + ' ...')
} else if (Name === '') {
console.log("Please insert your name")
} else if (Age === '' ) {
console.log("Please insert your age")
}