如何判断js的类型?

时间:23-02-22 栏目:Javascript 作者:zongyan86 评论:0 点击: 2,366 次

我最常用的方式:

1
2
3
function getType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let num = 1;
console.log(getType(num)); // "Number"

let str = "Hello World";
console.log(getType(str)); // "String"

let arr = [1, 2];
console.log(getType(arr)); // "Array"

let obj = { name: "sand" };
console.log(getType(obj)); // "Object"

let func = function() {};
console.log(getType(func)); // "Function"

let n = null;
console.log(getType(n)); // "Null"

let u = undefined;
console.log(getType(u)); // "Undefined"


声明: 本文由( zongyan86 )原创编译,转载请保留链接: 如何判断js的类型?

关注我们