由于被标记为正确的答案包含一个小错误,因此我最好尝试提出解决方案。我有两个选择,一个接受一个字符串,另一个接受一个字符串或一个数字,因为我认为很多人在JavaScript中混合字符串和数字。
步骤: - 如果对象为null,则为空或空字符串。 - 如果类型不是字符串(或数字),则其字符串值为空或空。注意:我们也可以在此处引发异常,具体取决于偏好。 - 如果修剪后的字符串值的长度小于1,则为空或空。
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
可能的重复[什么是最好的方式来测试一个空字符串jquery-out-the-bo X?(http://stackoverflow.com/questions/1812245/what-is-the-best-way-to-test-for-an-empty-string-with-jquery-out-of-the-box) – 2011-04-21 16:28:41
@ DanielA.White参数是一样的,但对于像我这样的C#开发人员来说,这个问题(带有它的标题)更可能被发现 – 2013-09-07 15:58:00