gpt4 book ai didi

javascript - new Boolean(name) 始终返回 true

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


let name = window.prompt("Please Enter Your Name ");
let age = parseInt(window.prompt("Please Enter Your age "));

const nameCheck = new Boolean(name);
const ageCheck = new Boolean(age);

if ( nameCheck && ageCheck )
{
console.log(`Hi ${name}, you were born in ${2020 - age}`)
}
else
{
alert("You either entered no name, or your age was not a number");
}

即使我故意输入空字符串或年龄字母,if block 始终计算为 true 并执行。我认为空字符串在转换为 Boolean 时必须计算为 false ?

最佳答案

Boolean 并没有像你想象的那样做。它是一个对象,并且对象总是真实的:

> typeof new Boolean(false)
"object"
> if (new Boolean(false)) console.log("It's true!");
It's true!

要将值转换为原始 boolean 类型,常见的方法是将其取反两次:

const nameCheck = !!name;

您还可以将 Boolean 作为函数调用,但我会远离它,因为它不返回实际的 Boolean ,这相当令人困惑:

const nameCheck = Boolean(name);

关于javascript - new Boolean(name) 始终返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59794532/

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