代码实现
index.js
const myTypeof = function (value) {
let type = typeof value
if (value === null) { // null比较特殊,typeof null = 'object'
return 'null'
} else if (type === 'object') { // array、object、Date、RegExp 的typeof都为'object'
// Object.prototype.toString.call([])返回格式[object Array]
return Object.prototype.toString.call(value).replace(/^\[object\s(\w+)\]$/, '$1')
} else {
return type
}
}
测试例子
index.test.js
let myTyepeof = require('./index.js')
test('Number:', () => {
expect(myTyepeof(123)).toBe('number')
})
test('String:', () => {
expect(myTyepeof('123')).toBe('string')
})
test('Boolean:', () => {
expect(myTyepeof(true)).toBe('boolean')
})
test('Null:', () => {
expect(myTyepeof(null)).toBe('null')
})
test('Undefined:', () => {
expect(myTyepeof(undefined)).toBe('undefined')
})
test('Arrary:', () => {
expect(myTyepeof([1, 2, 3])).toBe('Array')
})
test('Object:', () => {
expect(myTyepeof({a:1})).toBe('Object')
})
test('Date:', () => {
expect(myTyepeof(new Date())).toBe('Date')
})
test('RegExp:', () => {
expect(myTyepeof(new RegExp())).toBe('RegExp')
})
test('Symbol', () => {
expect(myTyepeof(Symbol())).toBe('symbol')
})