知识点:变量类型、变量计算
变量类型
- 值类型 VS 引用类型(对象、数组、函数)
- typeof 运算符详解
变量计算
- 强制类型转换
- 字符串拼接
- == 运算符
- if 语句
- 逻辑运算
值类型:每个变量都能存储各自的值,不会相互影响。
var a = 100;
var b = a;
a = 200;
console.log(b); // 100
引用类型:只有一个存储地址,a 和 b 同时指向对象。 => 共用空间
var a = {age:20};
var b = a;
b.age = 21;
console.log(a.age); // 21
typeof 运算符:
- 注意 null 也是一个 object 类型
- typeof 只能区分值类型的详细类型(前四行),针对引用类型则无能为力
- 针对后四行,只能区分出 function,因为函数是一个非常特殊的引用类型
typeof undefined // undefined
typeof 'abc' // string
typeof 123 // number
typeof true // boolean
typeof {} // object
typeof [] // object
typeof null // object
typeof console.log // function
字符串拼接:
var a = 100 + 10 // 110
var b = 100 + '10' // '10010'
== 运算符:(下面的三个例子看起来都很奇怪,一定要慎用“==”,因为“==”两端都会先转换成 false)
100 == '100' // true
0 == '' // true
null == undefined // true
if 语句:所有经过 if 判断的变量,都会进行逻辑运算的强制类型转换,转换为 true 或者 false。
var a = true
if (a) {
// .... 会执行if语句
}
var b = 100
if (b) {
// .... 会执行if语句
}
var c = ''
if (c) {
// .... 不会执行if语句
}
逻辑运算符:与或非
console.log(10 && 0) // 0
console.log('' || 'abc') // 'abc'
console.log(!window.abc) // true
// 判断一个变量会被当做 true 还是 false
var a = 100
console.log(!!a)