判斷引數(String、Array、Object)是否為undefined或者值為空
阿新 • • 發佈:2019-01-31
有時候我們會遇到這樣的情況:在一些前端控制元件要提交資料到伺服器端的資料驗證過程中,需要判斷提交的資料是否為空。如果是普通表單的字串資料,只需要在
trim
後判斷 length
即可,而這裡需要的資料可以是各種不同的型別(數字、字串、陣列、物件等等),通過
JSON.stringify(data)
進行序列化後再傳遞。
在這裡定義如下的資料值為“空值”:
- undefined
- null
- 空字串及純空白字串:''、' ' 等。
- 空陣列:[]
- 空物件:{}
對於除此以外的資料值,均認為不為空。
其中 null
和 undefined
很容易識別,但對於其他型別,我們須要得到其資料型別才能用相應的方法去檢測資料是否為空。最容易想到的方法就是利用typeof
if(typeof data === 'number') {
//deal with numbers
}
但 typeof
返回的型別字串只有 'object'、'function'、'number'、'boolean'、'string'、'undefined' 這六種,很多原生物件如 Date、RegExp 物件無法與用 {} 建立的物件進行區分。另外,typeof
對於一些基本資料型別如 (String、Number、Boolean) 與其對應的基本包裝型別資料會分別返回不同值,如:
console.log(typeof false); //'boolean'
console.log(typeof new Boolean(false)); //'object'
console.log(typeof 1); //'number'
console.log(typeof new Number(1)); //'object'
console.log(typeof ''); //'string'
console.log(typeof new String('')); //'object'
這對我們的判斷也有一定的影響。
用 instanceof
?這隻能判斷物件,而且存在多 frame 時多個同類物件不共享 prototype 的問題,從其他 frame 中取得的物件無法正確判斷。
還好,還有一個最簡單也最可靠的方法:Object.prototype.toString
。對於不同型別的資料,這個方法可以返回 '[object Object]'、'[object Array]'、'[object String]' 這樣的字串,非常方便判斷。需要注意的是,在 IE8 及其以下瀏覽器中,這個方法對於null
、undefined
、window
等都會返回 '[object Object]',不過還好,這並不影響我們使用它判斷空物件。
下面直接上程式碼,說明就看註釋吧。
var isEmptyValue = function(value) {
var type;if(value == null) { // 等同於 value === undefined || value === null
return true;
}
type = Object.prototype.toString.call(value).slice(8, -1);
switch(type) {
case 'String':
return !$.trim(value);
case 'Array':
return !value.length;
case 'Object':
return $.isEmptyObject(value); // 普通物件使用 for...in 判斷,有 key 即為 false
default:
return false; // 其他物件均視作非空
}
};