前言
纪录一些检查型别的方法,以及阵列去重比较乾净的写法
大纲
typeof 检查型别检查是否为 undefined检查是否为 null检查是否为 Object检查是否为 Array / 为空阵列阵列去重 indexOf() / includes()阵列去重 filter()阵列去重 ES6 Set (推荐)typeof 检查型别
可以检查 字串、数字、布林値typeof null 结果为 'object'typeof function(){} 结果为 'function ' const str = 'String' typeof str //'string' typeof NaN // 结果为 'number' typeof null // 结果为 'object' typeof function(){} // 结果为 'function '
检查是否为 undefined
typeof // 使用 let , const 宣告不给予值会直接喷错 var test typeof test // 'undefined' if(typeof test !=='undefined'){ // test is defined }
检查是否为 null
Falsy包含: 正负0,'',"",null,undefined,false,NaNFalsy 之外 Boolean() 后皆为正,包含物件因此 Boolean() 为 false 且 typeof 为物件者为 null const test = null; // 先判断是否为 Falsy 在判断是否 typeof 回传 object if (!test && typeof test === 'object') { console.log('Var is null'); }
检查是否为 Object
注意!! 必须排除 null 的可能性 const nullObj = null // 不会喷 console const obj = {} // 会喷 console if(typeof obj === 'object' && obj !== null){ console.log('Var is Object') }
检查是否为 Array / 为空阵列
isArray 回传 Boolean值length 利用长度判断是否为空阵列stack overflow 参考资料 const arr = [1] Array.isArray(arr) // true // 先判断是否为阵列 或者存在 // length 为 0 时 falsy 经过 ! 转为 true // 因此 arr 空阵列时会符合结果 if ( arr && !arr.length) { console.log('Var is Empty Array') } if (arr && arr.length) { console.log('Var is Array But Not Empty') }
阵列去重
indexOf() includes()
includes 回传 BooleanindexOf 回传 Index 无则-1 const arr = [1, 1, 2, 2, 3, 4, 5, 6] const includesArray = [] const indexOfArray = [] arr.forEach((el) => { // 当 includes 为 false 即不在暂存阵列时,将其加入 if (!includesArray.includes(el)) { includesArray.push(el) } // 当 indexOf 为 -1 即不在暂存阵列时,将其加入 if (indexOfArray.indexOf(el) < 0) { indexOfArray.push(el) } }) console.log(includesArray) console.log(indexOfArray)
filter()
filter 自身会产生 新阵列,省去自行建立同样用 indexOf() / includes 去判断是否存在 const filterArr = arr.filter(function(el, index, array) { return array.indexOf(el) === index }) console.log(filterArr)
ES6 Set
Set 为新的资料结构,类似阵列,但成员值不重複IE 11 有支援!! // ES6 SET const arr = [1, 1, 2, 2, 3, 4, 5, 6] const setArr = Array.from(new Set(arr)) console.log(setArr)