【js基础】之变量类型和计算

1.数据类型

ECMAScript定义了6种数据类型,包括:jquery

  • 基本数据类型:Undefined、Null、Boolean、Number、String;
  • 复杂数据类型:Object;

2.typeof操做符

typeof操做符可区分值类型,对于引用数据类型没法区分(只能区分出引用类型中的function)。数组

  • 'undefined',若是这个值未定义;
  • 'boolean',若是这个值是布尔值;
  • 'string',若是这个值是字符串;
  • 'number',若是这个值是数值;
  • 'object',若是这个值是对象或者null;
  • 'function',若是这个值是函数;

*判断一个对象(引用类型)是否为数组:arr instanceof Array,返回true、false。函数

typeof undefined;//undefined
typeof 'abc';//string
typeof 123;//number
typeof true;//boolean
typeof {};//object
typeof [];//object
typeof null;//object
typeof console.log;//function

3.值类型与引用类型

  • 值类型(Number,String,Boolean,Undefined)
  • 引用类型(Object,Array,Function)
//值类型(Number,String,Boolean,Undefined)
var a = 100;
var b = a;
a = 200;
console.log(a);//200
console.log(b);//100

//引用类型(Object,Array,Function)
var a = {age:20};
var b = a;
b.age = 21;
console.log(a.age);//21
console.log(b.age);//21

4.类型转换

  • 字符串拼接
  • == 运算符
  • if 语句
  • 逻辑运算
//1.字符串拼接
var a = 100 + 10;//110
var b = 100 + '10';//10010

//2.== 运算符
100 == '100'; //true
0 == '';//true
null == undefined;//true

0 === '';//false
null === undefined;//false

//3.if 语句
var a = true;if(a){}
var b = 100;if(b){}
var c = '';if(c){}

//4.逻辑运算符
console.log(10&&0);//0
console.log(''||'abc');//'abc'
console.log(!window.abc);//true

//判断一个变量会被当作true仍是false
var a = 100;
console.log(!!a);

5.区分 === 和 ==

==会发生类型转换,===没有类型转换。code

if(obj.a == null){
    //这里至关于判断了obj.a === null || obj.a === undefined;简写形式
    //这是 jquery 源码中推荐的写法
}

6.JS中的内置函数

  • Object
  • Array
  • Boolean
  • Number
  • String
  • Function
  • Date
  • RegExp
  • Error

7.JS 中的内置对象

  • Math
  • JSON

8.如何理解JSON

JSON是一种数据格式,也是一个 JS 对象,有如下两个API。对象

  • JSON.stringify({a:10,b:20}) //把对象转为字符串
  • JSON.parse('{"a":10,"b":20}') //把字符串转为对象
技巧:
可将if语句转换为false的有if( 0){}、if( NaN){}、if( ''){}、if( null){}、if( undefined){}、if( false){}
相关文章
相关标签/搜索