林间有风

郭朝夕的日记小站

  • 首页
  • 关于
  • 标签
  • 归档

抽象一个类型判断库

发表于 2023-02-21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export function type(x) {
const t = typeof x
if (x === null) {
return 'null'
}
if (t !== 'object') {
return t
}
const toString = Object.prototype.toString
const innerType = toString.call(x).slice(8, -1)
const innerLowType = innerType.toLowerCase()

if (['String', 'Boolean', 'Number'].includes(innerType)) {
return innerType
}

if (typeof x?.constructor?.name === 'string') {
return x.constructor.name
}

return innerLowType
}

实现一个深拷贝

发表于 2023-02-20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 获取数据类型的函数
*/
function type (data) {
return Object.prototype.toString.call(data).slice(8, -1).toLowerCase()
}

function clone(source) {
const t = type(source)
if (t !== 'object' && t !== 'array') {
return source
}
let target;
// 如果参数是一个Object类型
if (t === 'object') {
target = {}
// 对象的遍历方法
for (let i in source) {
if (source.hasOwnProperty(i)) {
target[i] = clone(source[i])
}
}
} else {
target = []
// 数组的遍历方法
for (let i = 0; i < source.length; i++) {
target[i] = clone(source[i])
}
}
return target
}
上一页1…67

62 日志
19 标签
© 2025 郭朝夕
冀ICP备18008237号