来源对象的应用规则是从左到右,随后的下一个对象的属性会覆盖上一个对象的属性。
``ts`
assign(
{},
{ x: 1 },
{ y: 2 },
{ x: 5, z: 9 },
)
// => { x: 5, y: 2, z: 9 }
#### autoSize
源码 | API | 回目录
自适应页面:页面基于一张设计图但需做多款机型自适应,元素尺寸使用rem进行设置
`ts`
autoSize(width); // 修改body当中的字体大小
#### base64Decode
源码 | API | 回目录
返回 base64 解码后的字符串。`ts`
base64Decode('5Lit5Zu9') // => 中国
base64Decode('8J+RqOKAjfCfkrs=') // => 👨💻
#### base64Encode
源码 | API | 回目录
返回 base64 编码后的字符串。`ts`
base64Encode('中国') // => 5Lit5Zu9
base64Encode('👨💻') // => 8J+RqOKAjfCfkrs=
#### base64UrlDecode
源码 | API | 回目录
返回 base64url 解码后的字符串。`ts`
base64UrlDecode('5Lit5Zu9') // => 中国
base64UrlDecode('8J-RqOKAjfCfkrs') // => 👨💻
#### base64UrlEncode
源码 | API | 回目录
返回 base64url 编码后的字符串。`ts`
base64UrlEncode('中国') // => 5Lit5Zu9
base64UrlEncode('👨💻') // => 8J-RqOKAjfCfkrs
#### buildQueryUrl
源码 | API | 回目录
创建 URI 带查询字符串。
`ts`
buildQueryUrl("/sample", {id:123,typeId:2343}) // => /sample?id=123&typeId=2343
buildQueryUrl("/sample?cc=222", {id:123,typeId:2343}) // => /sample?id=123&typeId=2343&cc=222
#### checkPwdLevel
源码 | API | 回目录
@description 检测密码强度
`ts`
checkPwdLevel(
"abc134"
)
// => 2
#### chunk
源码 | API | 回目录
将 arr 拆分成多个 size 长度的区块,并将它们组合成一个新数组返回。
如果 arr 无法等分,且设置了 filler 函数,剩余的元素将被 filler 函数的返回值填充。`ts`
const arr = [1, 2, 3, 4, 5, 6]
chunk(arr, 2) // => [[1, 2], [3, 4], [5, 6]]
chunk(arr, 3) // => [[1, 2, 3], [4, 5, 6]]
chunk(arr, 4) // => [[1, 2, 3, 4], [5, 6]]
chunk(arr, 4, index => index) // => [[1, 2, 3, 4], [5, 6, 0, 1]]
#### clamp
源码 | API | 回目录
返回限制在最小值和最大值之间的值。
`ts`
clamp(50, 0, 100) // => 50
clamp(50, 0, 50) // => 50
clamp(50, 0, 49) // => 49
clamp(50, 51, 100) // => 51
#### clone
源码 | API | 回目录
@description 深拷贝
`ts`
clone(
[1,2,3]
)
// => [1,2,3]
#### createURIQuery
源码 | API | 回目录
创建 URI 查询字符串。
`ts`
createURIQuery({ x: 1, y: 'z' }) // => x=1&y=z
#### debounce
源码 | API | 回目录
创建一个去抖函数,将触发频繁的事件合并成一次执行。
该函数被调用后,计时 wait 毫秒后调用 fn 函数。若在 wait 毫秒内该函数再次被调用,则重新开始计时。
一个应用场景:监听输入框的 input 事件发起网络请求。`ts`
document.querySelector('#input').oninput = debounce(
e => {
console.log(e.target.value)
},
500,
)
#### decryptChar
源码 | API | 回目录
字节简单加密操作
`ts
const encryptStr = new encryptChar("%E9%9A%94%EB%86%82%F0%98%80%83%F0%9C%B8%AC"); // 隔壁老王
`
#### defaultTo
源码 | API | 回目录
检查 value 是否是 null、undefined、NaN,是则返回 defaultValue,否则返回 value。`ts`
defaultTo(1, 2) // => 1
defaultTo(NaN, 2) // => 2
defaultTo(null, 2) // => 2
defaultTo(undefined, 2) // => 2
#### digitUppercase
源码 | API | 回目录
@description 金额转大写
`ts`
digitUppercase(
51551456.23
)
// => 伍仟壹佰伍拾伍万壹仟肆佰伍拾陆元贰角叁分
#### encryptChar
源码 | API | 回目录
字节简单加密操作
`ts
const encryptStr = new encryptChar("隔壁老王"); // "%E9%9A%94%EB%86%82%F0%98%80%83%F0%9C%B8%AC"
`
#### endsWith
源码 | API | 回目录
检查 str 是否以 needle 结尾。`ts`
endsWith('hello', 'llo') // => true
endsWith('hello', 'he') // => false
#### entitiestoUtf16
源码 | API | 回目录
用于解析出 emoji表情 把上面转的16位 直接转出来
`ts`
entitiestoUtf16("adfa😢babasfd"); // => adfa😢babasfd
#### fill
源码 | API | 回目录
使用 value 来填充(替换) arr,从 start 位置开始, 到 end 位置结束(但不包括 end 位置)。`ts`
fill(Array(5), () => 1) // => [1, 1, 1, 1, 1]
fill(Array(3), (value, index) => index) // => [0, 1, 2]
#### fillZero
源码 | API | 回目录
补零操作
`ts`
fillZero(169,5); // 结果 00169
#### filterXss
源码 | API | 回目录
过滤XSS
`ts`
filterXss(text); //返回过滤后的text
#### firstWordLower
源码 | API | 回目录
@description 首字母小写
`ts`
firstWordLower(
" ABC "
)
// => "abc"
#### firstWordUpper
源码 | API | 回目录
@description 首字母小写
`ts`
firstWordUpper(
" aasdfasdf "
)
// => "Aasdfasdf"
#### flexible
源码 | API | 回目录
移动端屏幕适配。
#### forOwn
源码 | API | 回目录
遍历对象的可枚举属性。若遍历函数返回 false,遍历会提前退出。
注:基于你传入的 obj,遍历函数中 key 的类型可能为 number,但在运行时,key 始终为 string,因此,你应该始终把 key 当作 string 处理。(为什么会这样?https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208)`ts`
forOwn(
{ x: '1', y: 2 },
(value, key) => {
console.log(key, value)
}
)
#### foramtNum
源码 | API | 回目录
格式化金钱
`ts`
foramtNum(123123123123); // 结果 123,123,123,123
#### formatEndTime
源码 | API | 回目录
现在距${endTime}的剩余时间
`ts`
formatEndTime("2019-7-18"); => { d: 0, h: 7, m: 8, s: 28, str: '0天 7小时 8分钟 28秒' };
#### from2Now
源码 | API | 回目录
${startTime}距现在的已过时间
`ts`
from2Now(new Date().getTime()) => 刚刚
#### getDeviceType
源码 | API | 回目录
返回设备类型
`ts`
// 获取设备类型
getDeviceType() // => pc
#### getFingerprint
源码 | API | 回目录
返回浏览器指纹
`ts`
// 获取浏览器指纹
getFingerprint() // => 401887683003324637-b8c4-411f-d6fc-c48d3ec59bb8
#### getGlobal
源码 | API | 回目录
获取全局对象。
`ts`
// 浏览器中
getGlobal() // => window
// Node 中
getGlobal() // => global
#### getIdCardInfo
源码 | API | 回目录
返回身份证信息
`ts`
getIdCardInfo("345955198706122245") // => {
'addrCode': 100101, //地址码信息,
'addr': '北京市东城区', //地址信息, 只在实例化时传入了GB2260时返回,
'birth': '1988-01-20', //出生年月日,
'sex': 1, //性别,0为女,1为男,
'checkBit': 'X', //校验位,仅当18位时存在,
'length': 18 //身份证类型,15位或18位
}
#### getLocation
源码 | API | 回目录
使用H5功能获取定位
`ts`
getLocation(optons={}).then().catch();
#### getNetWork
源码 | API | 回目录
返回设备网络
`ts`
// 获取设备网络
getNetWork() // => 4G
#### getOS
源码 | API | 回目录
返回设备的系统
`ts`
// 获取设备系统中
getOS() // => MacOSX
#### getOSVersion
源码 | API | 回目录
返回系统版本
`ts`
// 获取系统版本
getOSVersion() // => 11.0
#### getOrientationStatu
源码 | API | 回目录
返回屏幕方向
`ts`
// 获取屏幕方向
getOrientationStatu() // => 竖屏
#### getScrollTop
源码 | API | 回目录
获取滚动条距顶部的距离
`ts`
getScrollTop(); // 700
#### getType
源码 | API | 回目录
检测 value 的类型。`ts`
getType(1) // => 'Number'
getType(true) // => 'Boolean'
getType([]) // => 'Array'
getType(/hello/) // => 'RegExp'
#### getUUID
源码 | API | 回目录
近回唯一值
注:ii = immediately invoke`ts`
getUUID() // => 6a9af9e7-80b6-4988-8543-86e5bda42050
#### groupBy
源码 | API | 回目录
根据 iteratee 返回的值对 data 进行分组。`ts`
groupBy(
[
{ type: 1, name: '石头' },
{ type: 3, name: '花生' },
{ type: 2, name: '鲸鱼' },
{ type: 1, name: '树木' },
{ type: 2, name: '鲨鱼' },
],
item => item.type,
)
// => {
// => 1: [
// => { type: 1, name: '石头' },
// => { type: 1, name: '树木' },
// => ],
// => 2: [
// => { type: 2, name: '鲸鱼' },
// => { type: 2, name: '鲨鱼' },
// => ],
// => 3: [
// => { type: 3, name: '花生' },
// => ],
// => }
#### has
源码 | API | 回目录
检查 key 是否是对象 obj 自身的属性。`ts`
const obj = { x: 1, 2: 'y' }
has(obj, 'x') // => true
has(obj, 2) // => true
has(obj, 'toString') // => false
#### humpToUnderline
源码 | API | 回目录
驼峰转下划线
`ts`
let src = humpToUnderline("apiHookGet"); // api_hook_get
#### ii
源码 | API | 回目录
立即调用函数并返回其返回值。
注:ii = immediately invoke`ts`
ii(() => 1) // => 1
#### inAndroid
源码 | API | 回目录
检查是否在 Android 设备中。`ts`
// Android 设备中
inAndroid() // => true
inAndroid(
() => console.log('你在 Android 设备中'),
)
#### inBrowser
源码 | API | 回目录
检查是否在浏览器环境中。
`ts`
// 浏览器中
inBrowser() // => true
inBrowser(
() => console.log('你在浏览器中'),
)
#### inIOS
源码 | API | 回目录
检查是否在 iOS 设备中。`ts`
// iOS 设备中
inIOS() // => true
inIOS(
() => console.log('你在 iOS 设备中'),
)
#### inNode
源码 | API | 回目录
检查是否在 Node 环境中。`ts`
// Node 中
inNode() // => true
inNode(
() => console.log('你在 Node 中'),
)
#### inWechatMiniProgram
源码 | API | 回目录
检查是否在微信小程序环境中。
`ts`
// 微信小程序中
inWechatMiniProgram() // => true
inWechatMiniProgram(
() => console.log('你在微信小程序中'),
)
#### inWechatWebview
源码 | API | 回目录
检查是否在微信浏览器环境中。
`ts`
// 微信浏览器中
inWechatWebview() // => true
inWechatWebview(
() => console.log('你在微信浏览器中'),
)
#### includes
源码 | API | 回目录
检索值 value 是否在数组 arr 中。`ts`
includes([1, 2, 3], 1) // => true
includes([NaN, 2, 3], NaN) // => true
includes([1, 2, 3], 4) // => false
检索可枚举属性值 value 是否在对象 obj 中。`ts`
includes({ x: 1, y: 2 }, 1) // => true
includes({ x: 1, y: 2 }, 3) // => false
检索值 value 是否在字符串 str 中。`ts`
includes('hello', 'h') // => true
includes('hello', 'll') // => true
includes('hello', '123') // => false
#### isArguments
源码 | API | 回目录
检查 value 是否是一个 arguments 对象。`ts`
function myFunction() {
console.log(isArguments(arguments)) // true
}
#### isArray
源码 | API | 回目录
检查 value 是否是一个数组。`ts`
isArray(['x']) // => true
isArray('x') // => false
#### isBoolean
源码 | API | 回目录
检查 value 是否是一个布尔值。`ts`
isBoolean(true) // => true
isBoolean(false) // => true
isBoolean('true') // => false
#### isChineseIDCardNumber
源码 | API | 回目录
检查 value 是否是合法的中国大陆居民 18 位身份证号码。`ts`
isChineseIDCardNumber('123456') // => false
#### isDate
源码 | API | 回目录
检查 value 是否是一个日期。`ts`
isDate(new Date()) // => true
#### isEmail
源码 | API | 回目录
检查 value 是否是一个邮件地址。`ts`
isEmail('hello@foo.bar') // => true
isEmail('hello@foo') // => false
#### isEmpty
源码 | API | 回目录
检查 value 是否是空值,包括:undefined、null、''、false、true、[]、{}。`ts`
isEmpty(undefined) // => true
isEmpty(null) // => true
isEmpty('') // => true
isEmpty(false) // => true
isEmpty(true) // => true
isEmpty([]) // => true
isEmpty({}) // => true
#### isEqualArray
源码 | API | 回目录
检查给定的数组的各项是否相等。
`ts`
isEqualArray([1], [1]) // => true
isEqualArray([1], [5]) // => false
#### isFinite
源码 | API | 回目录
检查 value 是否是原始有限数值。`ts`
isFinite(1) // => true
isFinite(Infinity) // => false
#### isFunction
源码 | API | 回目录
检查 value 是否是一个函数。`ts`
isFunction(() => {}) // => true
isFunction(2000) // => false
#### isHan
源码 | API | 回目录
检查 value 是否全是汉字。`ts`
isHan('hello') // => false
isHan('嗨咯') // => true
#### isIdCard
源码 | API | 回目录
检查 value 是否是一个合法的身份证件号`ts`
isIdCard('123456') // => false
#### isInteger
源码 | API | 回目录
检查 value 是否是一个整数。`ts`
isInteger(1) // => true
isInteger(1.2) // => false
isInteger(-1) // => true
#### isNaN
源码 | API | 回目录
检查 value 是否是 NaN。`ts`
isNaN(NaN) // => true
isNaN(2) // => false
#### isNegativeInteger
源码 | API | 回目录
检查 value 是否是一个负整数。`ts`
isNegativeInteger(-1) // => true
isNegativeInteger(1) // => false
#### isNil
源码 | API | 回目录
检查 value 是否是 null 或 undefined。`ts`
isNil(null) // => true
isNil(undefined) // => true
#### isNull
源码 | API | 回目录
检查 value 是否是 null。`ts`
isNull(null) // => true
#### isNumber
源码 | API | 回目录
检查 value 是否是一个数字。
注:NaN 不被认为是数字。`ts`
isNumber(1) // => true
isNumber(0.1) // => true
isNumber(NaN) // => false
#### isNumeric
源码 | API | 回目录
检查 value 是否是一个数值。
注:Infinity、-Infinity、NaN 不被认为是数值。`ts`
isNumeric(1) // => true
isNumeric('1') // => true
#### isObject
源码 | API | 回目录
检查 value 是否是一个对象。`ts`
isObject({}) // => true
isObject(() => {}) // => true
isObject(null) // => false
#### isPlainObject
源码 | API | 回目录
检查 value 是否是一个普通对象。`ts`
isPlainObject({}) // => true
isPlainObject(Object.create(null)) // => true
isPlainObject(() => {}) // => false
#### isPositiveInteger
源码 | API | 回目录
检查 value 是否是一个正整数。`ts`
isPositiveInteger(1) // => true
isPositiveInteger(-1) // => false
#### isPossibleChineseMobilePhoneNumber
源码 | API | 回目录
检测 number 是否可能是中国的手机号码。`ts`
isPossibleChineseMobilePhoneNumber(18000030000) // => true
isPossibleChineseMobilePhoneNumber(10086) // => false
#### isPossibleChineseName
源码 | API | 回目录
检测 value 是否可能是中国人的姓名,支持少数名族姓名中间的 · 号。`ts`
isPossibleChineseName('鲁') // => false
isPossibleChineseName('鲁迅') // => true
isPossibleChineseName('买买提·吐尔逊') // => true
#### isPromiseLike
源码 | API | 回目录
检查 value 是否像 Promise。`ts`
isPromiseLike(Promise.resolve()) // => true
#### isRegExp
源码 | API | 回目录
检查 value 是否是一个正则对象。`ts`
isRegExp(/hello/) // => true
isRegExp(new RegExp('hello')) // => true
#### isString
源码 | API | 回目录
检查 value 是否是一个字符串。`ts`
isString('') // => true
isString('hello') // => true
#### isSupportWebP
源码 | API | 回目录
检查 是否支持webP
`ts
isSupportWebP(); // true
`
#### isUndefined
源码 | API | 回目录
检查 value 是否等于 undefined。`ts`
isUndefined(undefined) // => true
isUndefined(void 0) // => true
#### isUrl
源码 | API | 回目录
检查 value 是否是一个有效的网址,仅支持 http、https 协议,支持 IP 域名。`ts`
isUrl('http://foo.bar') // => true
isUrl('https://foo.bar/home') // => true
#### keyBy
源码 | API | 回目录
根据 iteratee 返回的键对 data 进行分组,但只保留最后一个结果。`ts`
keyBy(
[
{ type: 1, name: '石头' },
{ type: 3, name: '花生' },
{ type: 2, name: '鲸鱼' },
{ type: 1, name: '树木' },
{ type: 2, name: '鲨鱼' },
],
item => item.type,
)
// => {
// => 1: { type: 1, name: '树木' },
// => 2: { type: 2, name: '鲨鱼' },
// => 3: { type: 3, name: '花生' },
// => }
#### keys
源码 | API | 回目录
返回 obj 的可枚举属性组成的数组。
注:基于你传入的 obj,返回的 key 的类型可能为 number,但在运行时,key 始终为 string,因此,你应该始终把 key 当作 string 处理。(为什么会这样?https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208)`ts`
keys({ x: 1, 2: 'y' }) // => ['x', '2'] 或 ['2', 'x']
#### last
源码 | API | 回目录
返回数组 arr 的最后一项。`ts`
last([1, 2, 3]) // => 3
#### loadResource
源码 | API | 回目录
加载图片、代码、样式等资源。
`ts`
loadResource([
'https://foo.bar/all.js',
'https://foo.bar/all.css',
'https://foo.bar/logo.png',
{
type: LoadResourceUrlType.js,
path: 'https://s1.foo.bar/js/full',
alternatePath: 'https://s2.foo.bar/js/full',
},
]).then(() => {
// 资源加载完成后的操作
})
#### lunar2solar
源码 | API | 回目录
农历年月日转农历公历数据 返回json
`ts`
lunar2solar(
2019, 6, 14
)
// => {
lYear: 2019,
lMonth: 6,
lDay: 14,
Animal: "猪",
IMonthCn: "六月",
IDayCn: "十四",
cYear: 2019,
cMonth: 7,
cDay: 16,
gzYear: "己亥",
gzMonth: "辛未",
gzDay: "甲寅",
isToday: true,
isLeap: false,
nWeek: 2,
ncWeek: "星期二",
isTerm: false,
Term: null,
astro: "巨蟹座"
}
#### mapValues
源码 | API | 回目录
映射对象的可枚举属性值为一个新的值。
`ts`
mapValues(
{ x: 1, y: 2 },
value => value + 10,
)
// => { x: 11, y: 12 }
对字符串进行md5加密
`ts`
md5("abc4651adfA&&*"); // 974f8a36c6c6942e267c54687e7fae03
#### memoize
源码 | API | 回目录
函数结果缓存。
`ts`
let i = 0
const fn = memoize(() => i++)
fn() // => 0
fn() // => 0
#### noop
源码 | API | 回目录
无操作函数。
`ts`
noop() // => undefined
#### offset
源码 | API | 回目录
获取一个元素的距离文档(document)的位置,类似jQ中的offset()
`ts`
const e = document.querySelecter(".cc");
offset(e); // => {left: 100, top:99}
#### omit
源码 | API | 回目录
创建一个从 obj 中剔除选中的可枚举属性的对象。`ts`
omit({ x: 1, y: 2 }, ['x']) // => { y: 2 }
#### pHandle
源码 | API | 回目录
对方法时行 promise包装 不带finally
`ts`
let pFun = promiseHandle(fun);
pfun().then().catch()
// or
let res = await pfun();
#### padEnd
源码 | API | 回目录
在 str 右侧填充字符。`ts`
padEnd('姓名', 4, '') // => 姓名*
#### padStart
源码 | API | 回目录
在 str 左侧填充字符。`ts`
padStart('姓名', 4, '') // => *姓名
#### parallel
源码 | API | 回目录
并行执行任务,同步任务、异步任务 皆可。`ts`
parallel([
() => 1,
async () => 'hello',
]).then(res => {
// => [1, 'hello']
})
#### parseCSSValue
源码 | API | 回目录
解析 CSS 值的数值和单位。`ts`
parseCSSValue('12px') // => { value: 12, unit: 'px' }
parseCSSValue(12) // => { value: 12, unit: 'px' }
parseCSSValue('12%') // => { value: 12, unit: '%' }
#### parseURIQuery
源码 | API | 回目录
解析 URI 查询字符串。
兼容以 ? 开头的查询字符串,因此你可以直接传入 location.search 的值。`ts`
parseURIQuery('x=1&y=z') // => { x: '1', y: 'z' }
parseURIQuery('?x=1&y=z') // => { x: '1', y: 'z' }
parseURIQuery(
'x=1&y=z',
parameters => ({
...parameters,
x: Number(parameters.x),
}),
) // => { x: 1, y: 'z' }
#### pick
源码 | API | 回目录
创建一个从 obj 中选中的可枚举属性的对象。`ts`
pick({ x: 1, y: 2 }, ['x']) // => { x: 1 }
#### placeBing
源码 | API | 回目录
获取Bing的占位符,图片来自:https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture
`ts`
placeBing() // => https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture
#### placeKitten
源码 | API | 回目录
给定大小获取占位猫咪图片,图片来自:https://placekitten.com/
`ts`
placeKitten(100) // => https://placekitten.com/100/100
给定宽高获取占位猫咪图片,图片来自:https://placekitten.com/
`ts`
placeKitten(100, 200) // => https://placekitten.com/100/200
#### pluck
源码 | API | 回目录
将数据中每一项的迭代值组合成一个数组返回。
`ts`
pluck(
[{ id: 1, name: 'Jay' }, { id: 2, name: 'Lily' }],
item => item.name,
) // => ['Jay', 'Lily']
将数据中每一项的迭代值组合成一个对象返回。
`ts`
pluck(
[{ id: 1, name: 'Jay' }, { id: 2, name: 'Lily' }],
item => item.name,
item => item.id,
) // => { 1: 'Jay', 2: 'Lily' }
#### plusXing
源码 | API | 回目录
字符串隐藏部分变**
`ts`
plusXing('pianduan',2,2) // pi**an
#### promiseHandle
源码 | API | 回目录
对方法时行 promise包装
`ts`
let pFun = promiseHandle(fun);
pfun().then().catch().finally();
// or
let res = await pfun();
#### randomString
源码 | API | 回目录
生成一个指定长度的随机字符串。
`ts`
randomString(8) // => m481rnms
#### range
源码 | API | 回目录
创建一个包含从 start 到 end,但不包含 end 本身范围数字的数组。`ts`
range(0, 5) // => [0, 1, 2, 3, 4]
range(0, -5, -1) // => [0, -1, -2, -3, -4]
#### repeat
源码 | API | 回目录
重复 n 次给定字符串。`ts`
repeat('a', 5) // => aaaaa
#### round
源码 | API | 回目录
对传入的数字按给定的精度四舍五入后返回。
`ts`
round(3.456) // => 3
round(3.456, 1) // => 3.5
round(3.456, 2) // => 3.46
round(345, -2) // => 300
#### roundDown
源码 | API | 回目录
对传入的数字按给定的精度向下取值后返回。
`ts`
roundDown(3.456) // => 3
roundDown(3.456, 1) // => 3.4
roundDown(3.456, 2) // => 3.45
roundDown(345, -2) // => 300
#### roundUp
源码 | API | 回目录
对传入的数字按给定的精度向上取值后返回。
`ts`
roundUp(3.456) // => 4
roundUp(3.456, 1) // => 3.5
roundUp(3.456, 2) // => 3.46
roundUp(345, -2) // => 400
#### safeGet
源码 | API | 回目录
处理obj报错的
`ts`
const obj = {
zz: null,
zzz: undefined,
zzzz: "hoho"
};
safeGet(obj, "zz") // null
#### sample
源码 | API | 回目录
从数组中随机获取一个元素。
`ts`
sample([1, 2, 3]) // => 1 或 2 或 3
从对象中随机获取一个可枚举属性的值。
`ts`
sample({ x: 1, y: 2, z: 3 }) // => 1 或 2 或 3
#### scrollTo
源码 | API | 回目录
在${duration}时间内,滚动条平滑滚动到${to}指定位置
`ts`
scrollTo(300, 50);
#### sequential
源码 | API | 回目录
顺序执行任务,同步任务、异步任务 皆可。`ts`
sequential([
() => 1,
async () => 'hello',
]).then(res => {
// => [1, 'hello']
})
#### setScrollTop
源码 | API | 回目录
设置滚动条距顶部的距离
`ts`
setScrollTop(200);
#### showEleBorder
源码 | API | 回目录
显示全部DOM边框:调试页面元素边界时使用
`ts`
showEleBorder();
#### shuffle
源码 | API | 回目录
打乱一个数组。
`ts`
shuffle([1, 2]) // => [1, 2] 或 [2, 1]
#### sleep
源码 | API | 回目录
等待一段时间。
`ts`
sleep(1000).then(() => {
// 等待 1000 毫秒后执行
})
#### solar2lunar
源码 | API | 回目录
公历年月日转农历数据 返回json
`ts`
solar2lunar(
2019, 7, 16
)
// => {
lYear: 2019,
lMonth: 6,
lDay: 14,
Animal: "猪",
IMonthCn: "六月",
IDayCn: "十四",
cYear: 2019,
cMonth: 7,
cDay: 16,
gzYear: "己亥",
gzMonth: "辛未",
gzDay: "甲寅",
isToday: true,
isLeap: false,
nWeek: 2,
ncWeek: "星期二",
isTerm: false,
Term: null,
astro: "巨蟹座"
}
#### startsWith
源码 | API | 回目录
检查 str 是否以 needle 开头。`ts`
startsWith('hello', 'he') // => true
startsWith('hello', 'llo') // => false
#### sum
源码 | API | 回目录
计算传入值的总和。
`ts`
sum([1, 2, 3]) // => 6
#### sumBy
源码 | API | 回目录
根据 iteratee 返回的结果计算传入值的总和。`ts`
sumBy(
[
{ count: 1 },
{ count: 2 },
{ count: 3 },
],
item => item.count,
)
// => 6
#### throttle
源码 | API | 回目录
创建一个节流函数,给函数设置固定的执行速率。
- 该函数首次被调用时,会立即调用 fn 函数,并记录首次调用时间。wait
- 该函数第二次被调用时:
- 如果该次调用时间在首次调用时间的 区间内,timer = setTimeout(操作, 时间差);wait
- 该函数再次被调用时:
- 如果该次调用时间在首次调用时间的 区间内,什么都不做;
- 否则,清除首次调用时间和计时器,回到第一步。
- 否则,清除首次调用时间,回到第一步。
一个应用场景:监听窗口的 resize 事件响应相关操作。`ts`
window.addEventListener(
'resize',
throttle(
() => console.log('窗口大小改变后的操作'),
1000,
),
)
#### timeDiff
源码 | API | 回目录
${startTime - endTime}的剩余时间,startTime大于endTime时,均返回0
`ts`
timeDiff("2019-7-15","2019-7-20" ) => { d: 5, h: 0, m: 0, s: 0 }
#### times
源码 | API | 回目录
调用函数 n 次,将每次的调用结果存进数组并返回。`ts`
times(4, () => {
// 这里将会执行 4 次
})
#### toArray
源码 | API | 回目录
如果 value 是数组,直接返回;如果 value 不是数组,返回 [value]。`ts`
toArray([123, 456]) // => [123, 456]
toArray(123) // => [123]
toArray('hello') // => ['hello']
toArray(null) // => [null]
#### toDecimalNum
源码 | API | 回目录
@description 金额转大写
`ts`
toDecimalNum(
12305030388.9087
)
// => 12,305,030,388.9087
#### toggleCase
源码 | API | 回目录
@description 大小写切换
`ts`
toggleCase(
"abc"
)
// => ABC
#### trim
源码 | API | 回目录
@description 清除左右空格
`ts`
trim(
" abb "
)
// => abb
trim(
" ab b "
)
// => ab b
#### trimAll
源码 | API | 回目录
@description 清除所有空格
`ts`
trimAll(
" a b b "
)
// => abb
#### trimLeft
源码 | API | 回目录
@description 清除左空格
`ts`
trimLeft(
" a b b "
)
// => "a b b "
#### trimRight
源码 | API | 回目录
@description 清除右空格
`ts`
trimRight(
" a b b "
)
// => "a b b "
#### tryGet
源码 | API | 回目录
尝试执行 accessor 返回值,若其报错,返回默认值 defaultValue。`ts`
const obj = { x: 1 }
tryGet(() => obj.x, 2) // => 1
tryGet(() => obj.x.y, 2) // => 2
尝试执行 accessor 返回值,若其报错,返回 undefined。`ts`
const obj = { x: 1 }
tryGet(() => obj.x) // => 1
tryGet(() => obj.x.y) // => undefined
#### underlineToHump
源码 | API | 回目录
下划线转驼峰
`ts`
let src = underlineToHump("api_hook_get"); // apiHookGet
#### unique
源码 | API | 回目录
将给定的数组去重后返回。
`ts`
unique([1, 2, 1, 3]) // => [1, 2, 3]
#### utf16toEntities
源码 | API | 回目录
#### values
源码 | API | 回目录
返回 obj 自身可枚举属性值组成的数组。`ts`
values({ x: 1, 2: 'y' }) // => [1, 'y'] 或 ['y', 1]
#### windowResize
源码 | API | 回目录
H5软键盘缩回、弹起回调当软件键盘弹起会改变当前 window.innerHeight,监听这个值变化
`ts`
windowResize(()=>{
console.log("键盘弹出了")},() => {
console.log("键盘回弹了")});`
$3
#### Cache
源码 | API | 回目录
单一缓操作ts`
const cache = new Cache();
cache.setItem("name", "隔壁王叔",0);
cache.getItme("name"); // 隔壁王叔
cache.setItem("name", "隔壁王叔", 800);
await sleep(1000);
cache.getItem("name"); // null
#### CacheManger
源码 | API | 回目录
多缓存管理
`ts`
const cacheManger = new CacheManger();
cache.set("name", "隔壁王叔",0);
cache.get("name"); // 隔壁王叔
cache.set("name", "隔壁王叔", 800);
await sleep(1000);
cache.get("name"); // null
#### Cookie
源码 | API | 回目录
cookie操作
`ts`
const c = new Cookie();
c.cookie("name", "隔壁王叔", 1000 24 26); // 设置或是直接更新cookie
c.setCookie("name", "隔壁王叔", 1000 24 26)
c.getCookie("name"); // "隔壁王叔"
c.removeCookie("name"); // 移除cookie
#### DevicePixelRatio
源码 | API | 回目录
DevicePixelRatio操作windows页面在系统进行缩放后导致页面被放大的问题,通常放大比例是125%、150%
`ts`
DPR.init(); // windows页面在系统进行缩放后导致页面被放大的问题,通常放大比例是125%、150%
#### Disposer
源码 | API | 回目录
资源释放器。
`js`
const disposer = new Disposer()
const timer = setInterval(
() => console.log('ok'),
1000,
)
disposer.add(() => clearInterval(timer))
document.querySelector('#stop').onclick = () => {
disposer.dispose()
}
#### Encrypt
源码 | API | 回目录
encrypt操作
`ts`
const encrypt = new Encrypt();
encrypt.setAesString({name: "隔壁王叔",age:45}); // qrfXEUBWT7btkELMYzuUrYpawRMpRpWM2DA8T/FN6/aXNE4IpKQKIMpLfjoWHrXg
encrypt.getDAesString("qrfXEUBWT7btkELMYzuUrYpawRMpRpWM2DA8T/FN6/aXNE4IpKQKIMpLfjoWHrXg");{name: "隔壁王叔",age:45}
#### EventBus
源码 | API | 回目录
事件巴士,管理事件的发布与订阅。
`ts`
const bus = new EventBus<{
success: () => void,
error: (message: string) => void,
}>()
const unbindSuccessListener = bus.on('success', () => {
console.log('成功啦')
})
const unbindErrorListener = bus.once('error', message => {
console.error(message)
})
bus.emit('success')
bus.emit('error', '出错啦')
unbindSuccessListener()
bus.off('error')
#### FetchPack
源码 | API | 回目录
cookie操作
`ts`
const fetch = new FetchPack();
fetch.get("url"); // promise;
fet.post("url",body); // promise
#### Lock
源码 | API | 回目录
lock操作
`ts`
const eventLock = new Lock();
if(eventLock.lock(true, 100)) return; // true 上锁了 100ms后自动解锁
console.log("点击了有锁--" + Date.now());
#### LockDelay
源码 | API | 回目录
lock操作
`ts`
const eventLockDelay = new LockDelay();
if(eventLock.eventLockDelay(true, 1000)) return; // false 第一次没有上锁,一秒后自动上锁
console.log("点击了有锁--" + Date.now());
#### OnFire
源码 | API | 回目录
事件总线
`ts
const ee = new OnFire();
ee.on('click', (...values) => {});
ee.on('mouseover', (...values) => {});
ee.emit('click', 1, 2, 3);
ee.fire('mouseover', {}); // same with emit
ee.off();
`
#### Proxy
源码 | API | 回目录
`ts`
const proxy = new Proxy(host,port);
proxy.get(url);
proxy.post(url,body,session,headerType);
#### Store
源码 | API | 回目录
H5缓存操作
`ts`
const store = new Store();
store.sSet(key,value); // sessionStorage
store.lset(key,value); // localStorage
#### Validator
源码 | API | 回目录
数据对象验证器。
`ts`
interface Data {
name: string,
phoneNumber: string,
pass1: string,
pass2: string,
}
const ev = new validator([
{
key: 'name',
type: 'chineseName',
message: '请输入真实姓名',
},
{
key: 'phoneNumber',
type: 'chineseMobilePhoneNumber',
message: '请输入正确的手机号码',
},
{
key: 'phoneNumber',
test: async ({ phoneNumber }, { updateMessage }) => {
const result = await checkPhoneNumberAsync(phoneNumber)
if (!result.valid) {
updateMessage(result.message)
return false
}
},
message: '请输入正确的手机号码'
},
{
key: 'pass1',
test: ({ pass1 }) => pass1.length > 6,
message: '密码应大于6位',
},
{
key: 'pass2',
test: ({ pass1, pass2 }) => pass2 === pass1,
message: '两次密码应一致',
},
])
ev.validate({
name: '方一一',
phoneNumber: '18087030070',
pass1: '1234567',
pass2: '12345678'
}).then(res => {
// => { valid: false, unvalidRules: [{ key: 'pass2', test: ({ pass1, pass2 }) => pass2 === pass1, message: '两次密码应一致' }] }
})
#### Wechat
源码 | API | 回目录
对微信 JSSDK 的封装。
`ts`
const wechat = new Wechat()
getWechatConfigAsync().then(config => {
wechat.config(config)
})
wechat.updateShareData({
title: '分享标题',
desc: '分享描述',
link: '分享链接',
imgUrl: '缩略图地址',
})
wechat.invoke('scanQRCode').then(res => {
// => API 调用结果
})`
$3
#### AnyFunction
源码 | API | 回目录
任意函数类型。
#### AnyObject
源码 | API | 回目录
任意对象类型。
#### AsyncOrSync
源码 | API | 回目录
ts
`
// before
type X = PromiseLike
// after
type X = AsyncOrSync
`
#### Brand
源码 | API | 回目录
名义化类型。
ts
`
type User = { id: Brand
type Post = { id: Brand
type UserIdIsNumber = User['id'] extends number ? true: false // => true
type PostIdIsNumber = Post['id'] extends number ? true: false // => true
type PostIdIsNotUserId = Post['id'] extends User['id'] ? false : true // => true
T
#### Defined
源码 | API | 回目录
从 中排除 undefined 类型。
`ts
`
interface User {
gender?: 'male' | 'female',
}
// before
type UserGender = Exclude
// after
type UserGender = Defined
`
#### If
源码 | API | 回目录
条件类型。
ts
`
type X = 'x'
// before
type IsX = X extends 'x' ? true : false
// after
type IsX = If
T
#### IsNever
源码 | API | 回目录
检查 是否是 never 类型。
`ts
`
type X = never
// before
type XIsNever = [X] extends [never] ? true : false
// after
type XIsNever = IsNever
`
#### LiteralUnion
源码 | API | 回目录
字面量联合类型。
ts
`
// before: China, American 将得不到类型提示
type Country = 'China' | 'American' | string
// after: China, American 将得到类型提示
type Country = LiteralUnion<'China' | 'American', string>
`
#### Merge
源码 | API | 回目录
合并两个类型,后一个类型的定义将覆盖前一个类型的定义。
ts
`
type X = Merge<
{ x: number, y: number },
{ x: string, z: string }
>
// => { x: string, y: number, z: string }
T
#### Omit
源码 | API | 回目录
从接口 中去除指定的属性。
`ts
`
type X = Omit<
{ x: number, y: string, z: boolean },
'x' | 'z'
>
// => { y: string }
`
#### OneOrMore
源码 | API | 回目录
ts
`
// before
type X = number | number[]
// after
type X = OneOrMore
T
#### ValueOf
源码 | API | 回目录
返回接口 属性值的类型。
`ts
``
type V = ValueOf<{ x: number, y: string, z: boolean }>
// => number | string | boolean