由於被標記爲正確的答案包含一個小錯誤,因此我最好嘗試提出解決方案。我有兩個選擇,一個接受一個字符串,另一個接受一個字符串或一個數字,因爲我認爲很多人在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