数字
数字转字符串,添加千分位
function addSeparator(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
// 例
addSeparator(1234) // 1,234
字符串
统计某个字符在字符串中出现的次数
function countOcurrences(str = '', chr) {
if (!str) {
return 0;
}
let total = 0;
let lastLoaction = 0;
const firstLetter = `${chr}`[0];
lastLoaction = str.indexOf(firstLetter, lastLoaction) + 1;
while (lastLoaction) {
total += 1;
lastLoaction = str.indexOf(firstLetter, lastLoaction) + 1;
}
return total;
}
对象
判断是否是一个对象
function isObject(val: any): val is Object {
return val !== null && typeof val === 'object'
}
// 如果是Date 类型也会返回 true
判断是否是一个普通对象
function isPlainObject(val: any): val is Object {
return Object.prototype.toString.call(val) === '[object, Object]'
}
// 如果是Date类型,应该是'[object Date]'
判断浏览器
const isMac = /Mac/.test(navigator.platform);