gpt4 book ai didi

javascript - 如何根据变量是否定义来更改 console.log() 输出消息

转载 作者:行者123 更新时间:2023-11-28 12:16:08 25 4
gpt4 key购买 nike

您好,我是编码新手,我想尝试一下我学到了多少(不是很多)所以我做了这个:

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 显示“请插入您的姓名”,如果第二个提示留空,则如何使 console.log 显示“请插入您的年龄”。

如果这是一个愚蠢的问题,我很抱歉,但我两天前才开始,我将感谢您的帮助:)

最佳答案

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")
}
如果值为假(未定义、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 + ' ...')
}

关于javascript - 如何根据变量是否定义来更改 console.log() 输出消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068535/

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