Js判斷參數(String,Array,Object)是否為undefined或者值為空白_javascript技巧

來源:互聯網
上載者:User

有時候我們會遇到這樣的情況:在一些前端控制項要提交資料到伺服器端的資料驗證過程中,需要判斷提交的資料是否為空白。如果是普通表單的字串資料,只需要在 trim 後判斷 length 即可,而這裡需要的資料可以是各種不同的類型(數字、字串、數組、對象等等),通過 JSON.stringify(data) 進行序列化後再傳遞。

在這裡定義如下的資料值為“空值”:

•undefined
•null
•Null 字元串及純空白字串:''、'    ' 等。
•空數組:[]
•Null 物件:{}

對於除此以外的資料值,均認為不為空白。

其中 null 和 undefined 很容易識別,但對於其他類型,我們須要得到其資料類型才能用相應的方法去檢測資料是否為空白。最容易想到的方法就是利用typeof 操作符:

複製代碼 代碼如下:

<SPAN style="BACKGROUND-COLOR: rgb(255,255,255)">if(typeof data === 'number') {
  //deal with numbers
}</SPAN>

但 typeof 返回的類型字串只有 'object'、'function'、'number'、'boolean'、'string'、'undefined' 這六種,很多原生對象如 Date、RegExp 對象無法與用 {} 建立的對象進行區分。另外,typeof 對於一些基礎資料型別 (Elementary Data Type)如 (String、Number、Boolean) 與其對應的基本封裝類型資料會分別返回不同值,如:
複製代碼 代碼如下:

<SPAN style="BACKGROUND-COLOR: rgb(255,255,255)">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'</SPAN>

這對我們的判斷也有一定的影響。

用 instanceof?這隻能判斷對象,而且存在多 frame 時多個同類對象不共用 prototype 的問題,從其他 frame 中取得的對象無法正確判斷。

還好,還有一個最簡單也最可靠的方法:Object.prototype.toString。對於不同類型的資料,這個方法可以返回 '[object Object]'、'[object Array]'、'[object String]' 這樣的字串,非常方便判斷。需要注意的是,在 IE8 及其以下瀏覽器中,這個方法對於null、undefined、window 等都會返回 '[object Object]',不過還好,這並不影響我們使用它判斷Null 物件。

下面直接上代碼,說明就看注釋吧。

複製代碼 代碼如下:

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; // 其他對象均視作非空
            }
        };

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.