理解数据类型才能运用好 判断出数据类型才知道代码有什么用 当然类型还能转换
数据类型的分类
在 ECMAScript 中,变量可以存在两种类型的值,即原始值(基本数据类型)和引用值(复杂数据类型or对象数据类型or引用数据类型or类)。 这里要知道原始值和引用值 原始值:存储在栈(stack)中的简单数据段,也就是说,它们的值直接存储在变量访问的位置。 引用值:存储在堆(heap)中的对象,也就是说,存储在变量处的值是一个指针(point),指向存储对象的内存处。
基本(值)数据类型
String 任意字符串 Number 任意的数字 boolean true/false 只有这两个值 undefined undefined 唯一的值 null null 唯一的值
对象(引用)类型
Object 任意对象 存数据 Function 一种特别的对象(特别在能执行) 存代码 Array 一种特别的对象(数字下标,内部数据是有序的)
数据类型的判断
判断方法有三种:1.typeof 2.instanceof 3.=== typeof 只能判断基本数据类型(也能判断function),判断不出来null 因为 typeof null 结果的 object 返回数据类型的字符串 instanceof 只能判断复杂数据类型 A instanceof B B的开头字母必须大写 ===只能判断 undefined 和 null 因为这两个类型只有唯一一个值
String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//基本数据类型判断
var a="asd"
console.log(typeof a,typeof a ==="string"); //"string" true instanceof 不能用来判断基本数据类型
var b=123
console.log(typeof b); //"number"
var c=null
console.log(typeof c,c===null);//"object" true
var d //这里就表示 typeof 返回的是字符串
console.log(d,typeof d,d===undefined,typeof d==="undefined",typeof d===undefined); //undefined "undefined" true true false;
var e=true
var f=false
console.log(typeof e,e===false,e===true,typeof f,f===false,f=true); //"boolean" false true "boolean" true false
//对象数据类型判断
var obj={
name:"join",
age:18,
objs:[1,"asd",console.log],
objFunc:function(){
console.log("hello")
return function()
{
return "hi"
}
}
}
//A instanceof B B的开头字母必须大写
console.log(obj instanceof Object,obj.objFunc instanceof Function,typeof obj.name,typeof obj.age,typeof obj.objFunc,typeof obj.onjs[2],typeof obj.objs,obj.objs instanceof Array) //true true "string" "number" "function" "function" "object" true
//这里的 typeof obj.objFunc 返回"function" 说明 typeof 也能判断function
//我们这时候可以找到这里的 obj.objs[2] 是一个函数
//那么我们可以直接用
obj.objs[2]("hi") // hi
//相当于 console.log("hi")
console.log(obj.bb()()); //hi obj.bb()() 返回的是 hi console.log打印出来