JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
前面的所有答案都很好,但这会更好。使用双NOT运算符(!!):
if (!!str) {
// Some code here
}
或使用类型铸造:
if (Boolean(str)) {
// Code here
}
两者的功能相同。将变量类型转换为Boolean,其中str是一个变量。
对于null、undefined、0000、“”、false,它返回false。对于除空字符串之外的所有字符串值(包括“0”和“”等字符串),它都返回true
其他回答
开始于:
return (!value || value == undefined || value == "" || value.length == 0);
查看最后一个条件,如果值==“”,则其长度必须为0。因此,删除它:
return (!value || value == undefined || value == "");
但是等等!在JavaScript中,空字符串为false。因此,下降值==“”:
return (!value || value == undefined);
和undefined为true,因此不需要检查。因此,我们有:
return (!value);
我们不需要括号:
return !value
空字符串,未定义,null。。。
检查真实值:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
要检查错误值,请执行以下操作:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
空字符串(仅限!)
要检查是否正好为空字符串,请使用==运算符与“”进行严格相等比较:
if (strValue === "") {
// strValue was empty string
}
要严格检查非空字符串,请使用!==操作员:
if (strValue !== "") {
// strValue was not an empty string
}
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
或以函数形式:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
我不会太担心最有效的方法。使用最明确的意图。对我来说,这通常是strVar==“”。
根据Constantin的评论,如果strVar可以包含一个0整数值,那么这确实是一种意图明确的情况。
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
// Now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
这也是检查字段是否为空的通用方法。
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- getActivity()在Fragment函数中返回null
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象