string.Empty
的方法,或者只需要检查 ""
是否为空?string.Empty
的方法,或者只需要检查 ""
是否为空?我使用了一种组合方式,最快速的检查先执行。
function isBlank(pString) {
if (!pString) {
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);
}
开始翻译:
return (!value || value == undefined || value == "" || value.length == 0);
看最后一个条件,如果value == "",它的长度必须为0。因此将其删除:
return (!value || value == undefined || value == "");
但是!在JavaScript中,一个空字符串是false。因此,排除值等于“”:
return (!value || value == undefined);
并且 !undefined 的值为 true,因此不需要进行这个检查。因此我们有:
return (!value);
而且我们不需要括号:
return !value
value = false
或 value = 0
,你会根据问题返回正确的响应吗? - nerez我没有看到考虑到字符串中可能含有空字符的答案。例如,如果我们有一个空字符字符串:
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
为了测试它的空值,可以这样做:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
它适用于空字符串和空字符串,并且对所有字符串都可访问。此外,它可以扩展以包含其他JavaScript空或空格字符(即非断行空格、字节顺序标记、行/段落分隔符等)。
我在这里没有看到一个好的答案(至少对我来说不适合)。
所以我决定自己回答:
value === undefined || value === null || value === "";
你需要开始检查它是否未定义。否则,你的方法可能会出错,然后你可以检查它是否等于null或等于空字符串。
你不能只用!!或者if(value)
,因为如果你检查0
,它会给你一个假答案(0是false)。
因此,请将其包装在一个方法中,如下所示:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
附注:你不需要检查typeof,因为它进入方法之前就会出错并抛出异常。
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
String.IsNullOrEmpty = function (value) { ... }
您不希望将其放入字符串原型中,因为如果String类的实例为空,则会出现错误:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
我用以下值数组进行了测试。如果你有疑问,可以循环遍历它来测试你的函数。
// 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 JavaScript
['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; } }]
];
同时,我们可以编写一个函数来检查所有“空值”,例如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;
}
}
使用案例和结果。
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
使用空值合并运算符修剪空格:
if (!str?.trim()) {
// do something...
}
?.
没有更简单的了。如果 str
是 nullish,.trim()
将会抛出一个错误。 - sean试试这个:
export const isEmpty = string => (!string || !string.length);
所有这些答案都很好。
但我不能确定变量是一个字符串,是否只包含空格(对我很重要),并且可以包含'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
在jsfiddle上进行的示例。
empty(0)
和empty(7)
应该返回相同的值。 - Bennett McElweeempty("0")
必须返回 false
(因为它是一个非空字符串),但是 empty(0)
必须返回 true
,因为它是空的 :) - Andronempty
这个名称不准确且容易误导。有趣的是PHP也有一个命名不当的empty
函数,但是PHP的缺陷与JavaScript无关。 - Bennett McElwee没有isEmpty()
方法,您需要检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
类型检查是为了避免在test
为undefined
或null
时出现运行时错误。
test === ""
是等价的,而且更短。 - Flimm
null
或undefined
是空的呢?一个空字符串就是一个空字符串,它不是null
或undefined
。 - Flimm