console
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.move = function(x, y) {
this.x += x;
this.y += y;
}
var type = new Vue({
el: '#table',
data: {
bg: 'red',
md: ['typeof','Object.prototype.toString','constructor.name','instanceof'],
gd: [
{
t: undefined,
n: 'undefined'
},
{
t: null,
n: 'null'
},
{
t: true,
n: 'boolean'
},
{
t: 1,
n: 'number'
},
{
t: 'string',
n: 'string'
},
{
t: {},
n: 'object'
},
{
t: Symbol(),
n: 'Symbol()'
},
{
t: new Boolean(),
n: Boolean
},
{
t: new Number(),
n: Number
},
{
t: new String(),
n: String
},
{
t: new Array(),
n: Array
},
{
t: new Object(),
n: Object
},
{
t: new Function(),
n: Function
},
{
t: new Date(),
n: Date
},
{
t: new Error(),
n: Error
},
{
t: new RegExp(),
n: RegExp
},
{
t: new Point(1,2),
n: Point
}
]
}
})
<h1>JavaScript类型判断</h1>
<table id="table">
<tr>
<th>数据类型\判断方式</th>
<th v-for="(m,i) in md">{{ m }}</th>
</tr>
<tr v-for="(o,i) in gd">
<td>{{ o.t ? (i > 6 && i < 16 ? Object.prototype.toString.call(o.t).split('[')[1].replace(']','()').replace('object', 'new ') : i < 7 ? o.n : 'new Point(1,2)') : o.n }}</td>
<td :class="[(i !== 1 && i < 7) || i === 12 ? '' : bg]">{{ typeof o.t }}</td>
<td :class="[i < 16 ? '' : bg]">{{ Object.prototype.toString.call(o.t) }}</td>
<td :class="[o.t ? '' : bg]">{{ o.t ? o.t.constructor.name : 'x' }}</td>
<td :class="[i>6 ? '' : bg]">{{ i>6 ? (o.t instanceof o.n) : 'x' }}</td>
</tr>
<tr>
<td>总结</td>
<td>不能判断null<br />不能区分具体引用类型(Function除外)</td>
<td>不能判断自定义对象</td>
<td>不可判断undefined与null</td>
<td>不可判断原始类型</td>
</tr>
</table>
<h3>封装函数</h3>
<pre>
<code>
function typeOf(o) {
if(typeof o === 'undefined') return 'Undefined'
if(Object.prototype.toString.call(o) === '[object Null]') return 'Null'
return o.constructor.name
}
</code>
</pre>
body {
text-align: center
}
table {
width: 100%
}
td {
color: #fff;
background-color: green
}
.red {
background-color: red
}
pre {
text-align: left;
background-color: #000;
color: #fff
}