gpt4 book ai didi

javascript - 如何在 JavaScript 中将有效值记录到控制台

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

我正在尝试测试 id 值是什么,然后我在控制台中登录为“里面有东西”,就像这样。
那么我如何记录 id 中输入的内容。

如果未输入任何内容,则此代码:

if(comItem == undefined){
console.log('There Is Something in that value')
} else {
console.log('There is Nothing in that value')
}

我不知道该怎么做。

let comItem = 150;

if(comItem != undefined){
console.log('There Is Something in that value')
} else {
console.log('There is Nothing in that value')
}

最佳答案

听起来您想测试 comItem 是否是一个非空、非空白字符串。

JavaScript 对 == 运算符的定义非常宽松 - 并且它有助于不要使用 undefinednull 作为操作数,除非你真的知道你在做什么。

我建议阅读这些文章和 QA:

无论如何 - 好消息是仅使用 if( comItem ) { ... 就可以了,因为如果 comItem 它将计算为 true > 不是 null,也不是空字符串 "",但您需要单独检查 undefined(使用 typeof) 如果 var comItemlet comItem (或 const comItem)不能保证被定义,如下所示:

if( typeof comItem == 'undefined' ) {
console.log( );
}
else {
if( comItem ) {
console.log('There Is Something in that value')
}
else {
// `comItem` is either `undefined`, `null`, or an empty string
console.log('There is Nothing in that value')
}
}

如果您想测试非空白字符串,您将需要一个正则表达式,如下所示:

if( comItem ) {
if( /^\s+$/.test( comItem ) ) { // Test if the string contains only whitespace
console.log('Whitespace string');
}
else {
console.log('There Is definitely Something in that value');
}
}
else {
console.log('There is Nothing in that value');
}

请注意,您不能仅依赖 if(/\S/.test( comItem ) ) { ... 因为它对于 null 计算结果为 true .

所以总代码是:

if( typeof comItem == 'undefined' ) {
console.log( );
}
else {
if( comItem ) {
if( /^\s*$/.test( comItem ) ) {
console.log( 'Is whitespace' );
}
else {
console.log( 'Has a text value.' );
}
}
else {
console.log( 'Is null or empty' )
}
}

关于javascript - 如何在 JavaScript 中将有效值记录到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100920/

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