从深拷贝谈类型检测

实现深拷贝, 思路: 判断待拷贝的属性是否为数组或对象然后递归

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
function deepCopy (p, c = {}) {	
for(let i in p) {
if (typeof p[i] === 'object') {
c[i] = p[i].constructor === Array ? [] : {}
deepCopy(p[i], c[i])
} else {
c[i] = p[i]
}
}
return c
}

const testP = {
a: {
a1: 'a1'
},
b: ['b1', {
b2: 'b2'
}],
c: 'c'
}

const testRes = deepCopy(testP)

console.log(testRes)

typeof

  1. ‘number’
  2. ‘string’
  3. ‘boolean’
  4. ‘undefined’
  5. ‘null’
  6. ‘symbol’
  7. ‘object’
  8. ‘function’

其中数组和对象都会返回 ‘object’

instanceof

1
2
[] instanceof Array //true
[] instanceof Object //true

Object.prototype.toString.call

1
2
3
4
5
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call(1) // '[object Number]'
Object.prototype.toString.call('1') // '[object String]'
Object.prototype.toString.call(true) // '[object Boolean]'