先來回顧下js 的8大
基礎類型:Number、String、Boolean、Null、undefined、object、symbol、bigInt。
引用類型:
Object 、Array、Function、 Date
而js 也是一個類型自由的語言,定義一個變量可以賦值任何類型,然鵝這給開發也會帶來一些麻煩,如對一個數據進行為空校驗:
- JSON判斷:
/** * Checked if it is json object * Note: If it is a json, its format must be '{"name":"dex"}' or {"name":"dex"} * @param {Object} tragetObj */ function _isJSON(tragetObj) { if (typeof (tragetObj) === 'string') { try { var obj = JSON.parse(tragetObj) if (typeof (obj) === 'object' && obj) { return true } else { return false } } catch (e) { return false } } else if (typeof (tragetObj) === 'object' && !Array.isArray(tragetObj)) { return true } else { return false } }
- 數據為空驗證:
/** * Check if it is empty * and return true if it is * @param {Object} checkObj */ function isEmpty(checkObj) { if (!checkObj || !checkObj.length) { // Checke if it is ""、 undefined、 null 、NaN、 [] return true } else { if (_isJSON(checkObj)) { // check object let hasKey = '' if (typeof (checkObj) === 'string') { checkObj = JSON.parse(checkObj) } for (const key in checkObj) { hasKey = key break } if (!hasKey) { return true } else { return false } } else { if(checkObj === 'undefined' || checkObj === 'null'){ return true } return false } } }