专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 JavaScript数据类型判断方法

JavaScript数据类型判断方法

更新时间:2022-10-09 10:49:38 来源:动力节点 浏览850次

基本数据类型

简单数据类型:Number、String、Boolean、Null、Undefined、Symbol(ECMAScript 2015 新增)、BigInt(ECMAScript 2020 新增)

复杂数据类型:Arry、Object、Function

判断方法

注意:需要确定某些数据类型不推荐使用'==',推荐使用'==='。

以下打印结果为真

 // Number type 
var num = 12;
console.log(typeof num === 'number');
// console.log(num instanceof Number);// Can't judge 
//String type 
var str = "fgbb";
console.log(typeof str === 'string');
// console.log(str instanceof String);// Can't judge 
//Boolean type 
var tag = true;
console.log(typeof tag === 'boolean');
//Null
var nu = null;
console.log(typeof nu === 'object');
//Undefined
var un;
console.log(typeof un === 'undefined');
//Symbol
//Symbol Function stack cannot be used new command , because Symbol Is the original data type , Not object . You can take a string as an argument , For the newly created Symbol Provide a description , Used to display on the console or as a string , Easy to distinguish .
var sym = Symbol("sym");
sym = "any"
console.log(typeof sym === 'symbol');
//BigInt
var big = 12345n;
console.log(typeof big === 'bigint');
 // Arry
var arr = [1,2,3,4,5,6];
// Object
var obj = {

name: "Bob",
age: 18
}
// Function
function fn(){
}
// instanceof
console.log(obj instanceof Object);
console.log(arr instanceof Array);
// __proto__
console.log(arr.__proto__ === Array.prototype);
console.log(obj.__proto__ === Object.prototype);
console.log(fn.__proto__ === Function.prototype);
console.log(Array.prototype.isPrototypeOf(arr));
console.log(Object.prototype.isPrototypeOf(obj));
console.log(Function.prototype.isPrototypeOf(fn));
console.log(Object.getPrototypeOf(arr) === Array.prototype);
console.log(Object.getPrototypeOf(obj) === Object.prototype);
// console.log(Function.getPrototypeOf(fn) === Function.prototype);// It is impossible to judge whether it is a function 
// constructor
console.log(arr.constructor === Array);
console.log(obj.constructor === Object);
console.log(fn.constructor === Function);
// es6 New method of judging array 
console.log(Array.isArray(arr));

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>