首页 课程 师资 教程 报名

JavaScript数据类型判断方法

  • 2022-10-09 10:49:38
  • 1175次 动力节点

基本数据类型

简单数据类型: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));

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交