[生态建设] - js判断小技巧
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                [生态建设] - js判断小技巧
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                0、參考
說明: 從幾個易得的點出發,逐步向外擴展延申,保證代碼的可靠性
1、判斷是否為某個類型
// 判斷是否為 null const isNull = o => {return o === null; };// 判斷是否為 undefined const isUndefined = o => {return o === undefined; };// 判斷是否為 null or undefined const isNil = o => {return isNull(o) || isUndefined(o); };// 判斷是否為 string const isString = o => {return !isNil(o) && (typeof o === 'string' || o instanceof String); };// 判斷是否為 number const isNumber = o => {return !isNil(o) // 不為 null or undefined&& ((!isNaN(o) && isFinite(o)&& typeof o === 'number') || o instanceof Number); };// 判斷是否為 boolean const isBoolean = o => {return !isNil(o) && (typeof o === 'boolean' || o instanceof Boolean); };// 判斷是否為 array const isArray = o => {return !isNil(o) && Array.isArray(o); }// 判斷是否為 object const isObject = o => {return ({}).toString.call(o) === '[object Object]'; }// 判斷 o 為 O 的實例 const isType = (o, O) => {return !isNil(o) && o instanceof O; }// 判斷是否為 set const isSet = o => {return isType(o, Set); }// 判斷是否為 map const isMap = o => {return isType(o, Map); }// 判斷是否為 date const isDate = o => {return isType(o, Date); }2、判斷是否為空
數字和字符串可以使用o.length === 0來判斷,Set和Map型使用o.size === 0,Object類型使用Object.keys(o).length === 0來判斷,具體如下:
// 判斷是否為空 const isEmpty = o => {if (isArray(o) || isString(o)) {return o.length === 0;}if (isSet(o) || isMap(o)) {return o.size === 0;}if (isObject(o)) {return Object.keys(o).length === 0;}return false; }3、獲取第i個元素
主要是list、map、set類型
// 獲取列表的第i項 const getXItem = (i, list) => {if (!isArray(list) || !isSet(list) || !isMap(list)) {return undefined;}if (isArray(list)) {return list.slice(i)[0] || undefined;}if (isSet(list)) {return Array.from(list).slice(i)[0] || undefined;}if (isMap(list)) {return Array.from(list.value()).slice(i)[0] || undefined;} }// 獲取列表的最后一項 const getLastItem = list => {return getXItem(-1, list); }總結
以上是生活随笔為你收集整理的[生态建设] - js判断小技巧的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: java random算法_负载均衡--
- 下一篇: 大学只待成追忆,只是工作已半年,2016
