1.概述
js一共有6种数据类型,(es6又增加了Symbol类型的值)
数值number:整数和小数,比如1,1.32
字符串string:字符组成的文本,比如"hello world"
布尔值boolean:true,false
undefined:未定义,或者不存在
null:空值,无值
对象object:各种值组成的集合,可以分为3个子类型:狭义的对象object,数组array,函数function
2.typeof运算符
typeof运算符
instanceof运算符
Object.prototype.toString方法
以上3种方法可以确定一个值到底是什么类型
原始类型
返回number,string,boolean
示例:
typeof 123//number
typeof '123'//string
typeof false//boolean
返回函数
示例:
function f(){}
typeof f //function
返回undefined
示例:
typeof undefined //undefined
可以用typeof来检查一个没有生命的变量,而不报错,通常用在判断语句
示例:
if(typeof v==="undefined"){
}
返回object
示例:
typeof window //object
typeof {} //object
typeof [] //object
typeof null //object 本质上null不是对象类型,由于历史原因没法修改
typeof对数组和对象显示的结果都是object,怎么区分它们,可以用instanceof运算符
示例:
var o={};
var a=[];
o instanceof Array; //false
a instanceof Array; //true
2.null和undefined
null和undefined都表示没有,含义相似
示例:
var a=undefined;
//等同于
var a=null;
在if语句中它们都会被转为false
示例:
if(!undefined){
console.log('undefined is false');
}
//undefined is false
if(!null){
console.log('null is false');
}
//null is false
undefined ==null
//true
历史原因:null是一个表示无的对象,转为数值时是0;undefined是一个表示无的原始值,转为数值时为NaN
undefined表示未定义
示例:
var i;//i就是undefined
function f(x){
return x;
}
f();//undefined
//对象没有被赋值
var o=new Object();
o.p;//undefined
//函数没有返回值
function f(){}
f();//undefined
3.布尔值
下列运算符会返回布尔值
&&,||,!,===,!==,==,!=,>,>=,<,<=
常常布尔值用作流程控制
示例:
if(''){
console.log(true);
}
需要特别注意,空数组[]和空对象{}对应的布尔值,都是true
示例:
if([]){
console.log(true);
}
//true
if({}){
console.log(true);
}
//true