目录
js的数据类型
1、数据类型分为:基本数据类型、引用数据类型。基本数据类型的值存储在栈中;引用数据类型的值存储在堆中,栈中存储的是它的引用。
2、JavaScript 的数据类型,共有8种(截止2024年):number、string、boolean、undefined、null、symbol、bigint、object。
3、其中,基本数据类型:number、string、boolean、undefined、null、symbol、bigint;引用数据类型:object。
4、而object类型又可以细分为:函数function、数组array、狭义的对象object。
如何判断js的数据类型
JavaScript 有三种方法,可以确定一个值到底是什么类型:typeof、instanceof、Object.prototype.toString。
-
typeof运算符
typeof null; // 'object'
typeof 'undefined'; // 'string'
typeof undefined; // 'undefined'
typeof suibian; // 'undefined'
var a = 1;
typeof a; // 'number'
a = 'aa';
typeof a; // 'string'
typeof a === 'string'; // true
a = true;
typeof a; // 'boolean'
typeof Symbol(); // 'symbol'
typeof new Function(); // 'function'
typeof new Date(); // 'object'
typeof new Date() === 'object'; // true
-
instanceof运算符
[1,2,3] instanceof Array; // true
new Date() instanceof Date; // true
new Date() instanceof Object; // true
new Function() instanceof Function; // true
new Function() instanceof function; // false,注意Function的大小写
null instanceof Object; // false
"abc" instanceof String; // false
"abc" instanceof string; // Uncaught ReferenceError: string is not defined at <anonymous>:1:18
-
Object.prototype.toString方法
Object.prototype.toString.call(null); // '[object Null]'
var a = 1;
Object.prototype.toString.call(a); // '[object Number]'
JS、Java数据类型之间的区别
1、JS是弱数据类型的语言,声明变量时使用var,使用等号=对变量进行赋值。可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量,但是要注意只能用var声明一次。如果一个变量没有通过var就被使用,那么该变量就自动被声明为全局变量。现在也可以用let、const声明变量。变量名是大小写英文、数字、$和_的组合,且不能用数字开头,变量名不能是if、while等关键字。
2、Java是强数据类型的语言,声明变量时需要指定具体的数据类型。同一个变量再次赋值时,必须是属于该数据类型的值。
参考: