JS 判斷空字符串
在很多情景下,需要對字符串進行判空的操作,例如表單提交或獲取后端數值。
1、typeof 判斷 undefiend
typeof是一個運算符,有2種使用方式:typeof(表達式)和typeof 變量名,第一種是對表達式做運算,第二種是對變量做運算。
typeof的返回值
- 'undefined' --未定義的變量或值
- 'boolean' --布爾類型的變量或值
- 'string' --字符串類型的變量或值
- 'number' --數字類型的變量或值
- 'object' --對象類型的變量或值,或者null(這個是js歷史遺留問題,將null作為object類型處理)
- 'function' --函數類型的變量或值
var content;
if(typeof content === "undefined") //true
變量定義后為賦值即為 undefined
2、判斷null
var content = null;
if(typeof content === null) //true
3、trim()判斷空格
trim() 方法用於刪除字符串的頭尾空白符,空白符包括:空格、制表符 tab、換行符等其他空白符等。
var content = " "; //一列空格
if(typeof content.trim() === "") //true
4、總的寫法
綜上,上面的判斷順序不能變換,寫法如下:
if(typeof content === "undefined" || content === null || content.trim() === "") {
this.$message({
showClose: true,
message: '空字符串',
type: 'error'
});
}