个人觉得本期更像是自己对基础的一个查缺补漏,可以把一些常用的函数用到自己的项目中。
1、toNumber:以前自己的写法不严谨
const toNumber = (val) => {const n = parseFloat(val);return isNaN(n) ? val : n;};// 之前自己都会这样写const toNumber = (val) => {return Number(val)};
2、globalThis:对于globalThis的判断非常的严格,要考虑这么多的边界条件
let _globalThis;const getGlobalThis = () => {return (_globalThis ||(_globalThis =typeof globalThis !== 'undefined'? globalThis: typeof self !== 'undefined'? self: typeof window !== 'undefined'? window: typeof global !== 'undefined'? global: {}));};
3、isPromise:对于Promise的的判断更加严格
const isPromise = (val) => {return isObject(val) && isFunction(val.then) && isFunction(val.catch);};
4、转成字符串方法判断对象
const objectToString = Object.prototype.toString;const toTypeString = (value) => objectToString.call(value);const isPlainObject = (val) => toTypeString(val) === '[object Object]';
5、外加一些其他类型的判断
const isDate = (val) => val instanceof Date;const isFunction = (val) => typeof val === 'function';const isString = (val) => typeof val === 'string';const isSymbol = (val) => typeof val === 'symbol';const isObject = (val) => val !== null && typeof val === 'object';
6、对于类型判断这样更加严谨
var typeObject = {};"Boolean Number String Function Array Date RegExp Object Error Null Undefined".split(" ").map(function (item, index) {typeObject["[object " + item + "]"] = item.toLowerCase();})function type(obj) {if (obj == null) {return obj + "";}return typeof obj === "object" || typeof obj === "function" ?typeObject[Object.prototype.toString.call(obj)] || "object" :typeof obj;}// isFunction封装function isFunction(obj) {return type(obj) === "function";}// isObject封装function isObject(obj) {return type(obj) === "object";}
