cas*_*ora 2645 javascript null is-empty
我看到了这个帖子,但我没有看到JavaScript特定的例子.有一个简单string.Empty的JavaScript可用,还是只是检查的情况""?
bdu*_*kes 3323
如果您只想检查是否有任何价值,您可以这样做
if (strValue) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
如果您需要专门为在空空字符串检查,我想核对""是你最好的选择,使用的===运营商(让你知道这是,事实上,一个字符串你对比较).
if (strValue === "") {
//...
}
Run Code Online (Sandbox Code Playgroud)
小智 1060
为了检查字符串是否为空,null或未定义,我使用:
function isEmpty(str) {
return (!str || 0 === str.length);
}
Run Code Online (Sandbox Code Playgroud)
为了检查字符串是否为空,null或未定义,我使用:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
Run Code Online (Sandbox Code Playgroud)
用于检查字符串是空白还是仅包含空格:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
Run Code Online (Sandbox Code Playgroud)
小智 275
以上所有都很好,但这会更好.使用!!(而不是)运营商.
if(!!str){
some code here;
}
Run Code Online (Sandbox Code Playgroud)
或使用类型转换:
if(Boolean(str)){
codes here;
}
Run Code Online (Sandbox Code Playgroud)
两者都执行相同的功能,将变量类型转换为boolean,其中str是变量.
返回false的null,undefined,0,000,"",false.
返回true字符串"0"和空格"".
Sug*_*ran 98
如果你需要确保字符串不只是一堆空格(我假设这是用于表单验证),你需要对空格进行替换.
if(str.replace(/\s/g,"") == ""){
}
Run Code Online (Sandbox Code Playgroud)
Ate*_*ral 95
你能得到的最接近的东西str.Empty(前提是str是一个String)是:
if (!str.length) { ...
Run Code Online (Sandbox Code Playgroud)
小智 59
我用 :
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case typeof this == "undefined":
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 48
我在macOS v10.13.6 (High Sierra) 上对 18 个选定的解决方案进行了测试。解决方案的工作方式略有不同(对于极端情况输入数据),如下面的代码片段所示。
结论
!str,==,===和length是快速对于所有浏览器(A,B,C,G,I,J)test, replace)的解决方案charAt对于所有浏览器 (H,L,M,P) 来说都是最慢的在下面的片段中,我通过使用不同的输入参数比较了所选 18 种方法的结果
"" "a" " "- 空字符串、带字母的字符串和带空格的字符串[] {} f- 数组、对象和函数0 1 NaN Infinity - 数字true false - 布尔值null undefined并非所有经过测试的方法都支持所有输入案例。
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);Run Code Online (Sandbox Code Playgroud)
然后对于所有方法,我str = ""为浏览器 Chrome v78.0.0、Safari v13.0.4 和 Firefox v71.0.0执行速度测试用例- 你可以在这里在你的机器上运行测试
cll*_*pse 33
var s; // undefined
var s = ""; // ""
s.length // 0
Run Code Online (Sandbox Code Playgroud)
JavaScript中没有任何代表空字符串的内容.对任一个length(如果您知道var将始终是一个字符串)或反对进行检查""
小智 33
尝试:
if (str && str.trim().length) {
//...
}
Run Code Online (Sandbox Code Playgroud)
T.T*_*dua 33
功能:
function is_empty(x)
{
return (
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
Run Code Online (Sandbox Code Playgroud)
ps在Javascript中,不要在使用Line-Break之后
return;
Mos*_*hii 33
您可以使用lodash:_. isEmpty(value).
它涵盖了很多类似的情况下{},'',null,undefined等.
但它总是返回true的Number类型的Javascript基本数据类型一样_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)两者的回报true.
Chr*_*Noe 26
我不会太担心最有效的方法.使用最明确的意图.通常对我来说strVar == "".
编辑:根据Constantin的评论,如果strVar可能会有一些结果包含整数0值,那么这确实是那些意图澄清情况之一.
小智 19
你也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
Run Code Online (Sandbox Code Playgroud)
检查空字符串或用空格填充的字符串.
tfo*_*ont 17
很多答案,以及很多不同的可能性!
毫无疑问,快速和简单的实施赢家是: if (!str.length) {...}
但是,正如许多其他例子一样.最好的功能方法,我建议:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
{
return true;
}
else
{
return false;
}
}Run Code Online (Sandbox Code Playgroud)
我知道,有点过分了.
Tim*_*ene 16
var a;存在修剪出false spaces值,然后测试emptiness
if ((a)&&(a.trim()!=''))
{
// if variable a is not empty do this
}
Run Code Online (Sandbox Code Playgroud)小智 15
此外,如果您将填充空格的字符串视为"空".您可以使用此正则表达式进行测试:
!/\S/.test(string); // Returns true if blank.
Run Code Online (Sandbox Code Playgroud)
use*_*641 13
我经常使用这样的东西,
if (!str.length) {
//do some thing
}
Run Code Online (Sandbox Code Playgroud)
Abh*_*hra 12
从...开始:
return (!value || value == undefined || value == "" || value.length == 0);
Run Code Online (Sandbox Code Playgroud)
查看最后一个条件,如果 value == "",则其长度必须为 0。因此将其删除:
return (!value || value == undefined || value == "");
Run Code Online (Sandbox Code Playgroud)
可是等等!在 JavaScript 中,空字符串是假的。因此,丢弃值 == "":
return (!value || value == undefined);
Run Code Online (Sandbox Code Playgroud)
!undefined 是真的,所以不需要检查。所以我们有:
return (!value);
Run Code Online (Sandbox Code Playgroud)
我们不需要括号:
return !value
Run Code Online (Sandbox Code Playgroud)
sea*_*ean 10
使用空合并运算符修剪空格:
if (!str?.trim()) {
// do something...
}
Run Code Online (Sandbox Code Playgroud)
小智 10
在简单地检查空字符串的情况下
if (str.length){
//do something
}
Run Code Online (Sandbox Code Playgroud)
如果您还想简单地在支票中包含 null 和 undefined
if (Boolean(str)){
//this will be true when the str is not empty nor null nor undefined
}
Run Code Online (Sandbox Code Playgroud)
我没有注意到一个考虑到字符串中空字符可能性的答案.例如,如果我们有一个空字符串:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
Run Code Online (Sandbox Code Playgroud)
要测试其null,可以执行以下操作:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
Run Code Online (Sandbox Code Playgroud)
它适用于空字符串,并且在空字符串上,并且可以访问所有字符串.此外,它可以扩展为包含其他JavaScript空或空白字符(即不间断空格,字节顺序标记,行/段分隔符等).
所有这些答案都很好.
但我不能确定变量是一个字符串,不包含空格(这对我来说很重要),并且可以包含'0'(字符串).
我的版本:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Run Code Online (Sandbox Code Playgroud)
关于jsfiddle的示例.
如果一个人不仅需要检测空字符串而且还需要空白字符串,我将添加Goral的答案:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
Run Code Online (Sandbox Code Playgroud)
同时我们可以使用一个函数来检查所有'空,',如null,undefined,'','',{},[].所以我写了这个.
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
用例和结果.
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
Run Code Online (Sandbox Code Playgroud)
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Run Code Online (Sandbox Code Playgroud)
更新: 由于这个答案越来越流行,我想我也会写一个函数形式:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Run Code Online (Sandbox Code Playgroud)
小智 7
我经常使用类似的东西:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
Run Code Online (Sandbox Code Playgroud)
小智 7
试试这个
str.value.length == 0
Run Code Online (Sandbox Code Playgroud)
我使用组合,最快的检查是第一次.
function isBlank(pString){
if (!pString || pString.length == 0) {
return true;
}
// checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
Run Code Online (Sandbox Code Playgroud)
忽略空白字符串,您可以使用它来检查null,empty和undefined:
var obj = {};
(!!obj.str) //returns false
obj.str = "";
(!!obj.str) //returns false
obj.str = null;
(!!obj.str) //returns false
Run Code Online (Sandbox Code Playgroud)
简洁,它适用于未定义的属性,虽然它不是最易读的.
小智 7
我做了一些研究,如果将非字符串和非空/空值传递给测试器函数会发生什么.众所周知,(0 =="")在javascript中是正确的,但由于0是一个值而不是空或null,您可能想要测试它.
以下两个函数仅对undefined,null,empty/whitespace值返回true,对其他所有值返回false,如数字,布尔值,对象,表达式等.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
Run Code Online (Sandbox Code Playgroud)
存在更复杂的例子,但这些例子很简单并且给出了一致的结果.没有必要测试undefined,因为它包含在(value == null)检查中.您也可以通过将它们添加到String来模仿C#行为,如下所示:
String.IsNullOrEmpty = function (value) { ... }
Run Code Online (Sandbox Code Playgroud)
您不希望将它放在Strings原型中,因为如果String类的实例为null,则会出错:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error
Run Code Online (Sandbox Code Playgroud)
我测试了以下值数组.如果有疑问,你可以循环测试你的功能.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // valid number in some locales, not in js
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
Run Code Online (Sandbox Code Playgroud)
检查是否完全是一个空字符串:
if(val==="")...
Run Code Online (Sandbox Code Playgroud)
检查它是否为空字符串或无值的逻辑等效项(null,undefined,0,NaN,false,...):
if(!val)...
Run Code Online (Sandbox Code Playgroud)
您可以轻松地将其添加到JavaScript中的本机String对象中,并一遍又一遍地重复使用...
如果您想检查空字符串,则像下面的代码这样简单的事情就可以为您完成这项工作:''
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
Run Code Online (Sandbox Code Playgroud)
否则,如果您想同时检查''空字符串和' '空格,则只需添加即可trim(),例如下面的代码:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
Run Code Online (Sandbox Code Playgroud)
您可以这样称呼:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
Run Code Online (Sandbox Code Playgroud)
到目前为止,还没有像string.empty这样的直接方法来检查字符串是否为空。但是在您的代码中,您可以使用包装器检查是否为空字符串,例如:
// considering the variable in which your string is saved is named str.
if (str && str.length>0) {
// Your code here which you want to run if the string is not empty.
}
Run Code Online (Sandbox Code Playgroud)
使用此方法,您还可以确保字符串也未定义或为null。记住,未定义,null和empty是三件事。
尝试这个:
export const isEmpty = string => (!string || !string.length);
Run Code Online (Sandbox Code Playgroud)
没有isEmpty()方法,你必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
Run Code Online (Sandbox Code Playgroud)
类型检查是必要的,以避免运行时错误时test是undefined或null.
您可以验证以下方式并了解差异。
var j = undefined;
console.log((typeof j == 'undefined') ? "true":"false");
var j = null;
console.log((j == null) ? "true":"false");
var j = "";
console.log((!j) ? "true":"false");
var j = "Hi";
console.log((!j) ? "true":"false");Run Code Online (Sandbox Code Playgroud)
小智 6
这里有很多有用的信息,但在我看来,最重要的元素之一没有得到解决。
null, undefined, 和""都是假的。
在评估空字符串时,通常是因为您需要将其替换为其他内容。
在这种情况下,您可以期待以下行为。
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
Run Code Online (Sandbox Code Playgroud)
考虑到这一点,可以返回字符串是"", null, 或undefined(无效字符串)还是有效字符串的方法或函数就像这样简单:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
Run Code Online (Sandbox Code Playgroud)
我希望这会有所帮助。
检查它是否是字符串类型并且它是否不为空:
const isNonEmptyString = (val) => typeof val === 'string' && !!val
Run Code Online (Sandbox Code Playgroud)
不要假设您检查的变量是字符串.不要假设如果这个var有一个长度,那么它就是一个字符串.
问题是:仔细考虑您的应用必须做什么并且可以接受的内容.建立强大的东西.
如果你的方法/函数只应处理非空字符串,那么测试参数是否为非空字符串并且不做"技巧".
作为一个例子,如果你在这里不小心遵循一些建议会爆炸.
var getLastChar = function (str) {
if (str.length > 0)
return str.charAt(str.length - 1)
}
getLastChar('hello')
=> "o"
getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'
所以,我坚持下去
if (myVar === '')
...
您也应该始终检查类型,因为 JavaScript 是一种鸭子类型语言,因此您可能不知道数据在过程中何时以及如何更改。所以,这是更好的解决方案:
let undefinedStr;
if (!undefinedStr) {
console.log("String is undefined");
}
let emptyStr = "";
if (!emptyStr) {
console.log("String is empty");
}
let nullStr = null;
if (!nullStr) {
console.log("String is null");
}Run Code Online (Sandbox Code Playgroud)
该Underscore.js JavaScript库,http://underscorejs.org/,提供了一个非常有用的_.isEmpty()用于检查空字符串和其他空对象的功能。
参考:http : //underscorejs.org/#isEmpty
isEmpty
_.isEmpty(object)
如果可枚举对象不包含任何值(没有可枚举的自身属性),则返回 true。对于字符串和类似数组的对象 _.isEmpty 检查 length 属性是否为 0。
_.isEmpty([1, 2, 3]);
=> 假
_.isEmpty({});
=> 真
其他非常有用的 Underscore.js 函数包括:
_.isNull(object)_.isUndefined(value)_.has(object, key)小智 5
以下正则表达式是另一种解决方案,可用于 null、空或未定义的字符串。
(/(null|undefined|^$)/).test(null)
Run Code Online (Sandbox Code Playgroud)
我添加了这个解决方案,因为它可以进一步扩展以检查空值或某些值,如下所示。以下正则表达式正在检查字符串是否可以为空 null 未定义或它只有整数。
(/(null|undefined|^$|^\d+$)/).test()
Run Code Online (Sandbox Code Playgroud)
小智 5
我在这里看不到好的答案(至少不是一个适合我的答案),所以我决定自己回答:
value === undefined || value === null || value === "";
您需要开始检查它是否未定义,否则您的方法可能会爆炸,而不是检查是否等于null或等于空字符串
你不能拥有!或仅if(value) 当您检查后才0会给您一个错误的答案(0为错误)
这么说,用下面的方法包装它:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS。您不需要检查typeof,因为它甚至在进入方法之前都会爆炸。
小智 5
您可以使用 typeof 运算符和 length 方法来检查这一点。
const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
Run Code Online (Sandbox Code Playgroud)
试试这个代码:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2756353 次 |
| 最近记录: |