有人说,JavaScript 是唯一一门可以先用后学的编程语言。
1.2 内置类型
- 空值(null)
- 未定义(undefined)
- 布尔值( boolean)
- 数字(number)
- 字符串(string)
- 对象(object)
- 符号(symbol,ES6 中新增)
除对象之外,其他统称为"基本类型"。
用 typeof 运算符来查看值的类型,它返回的是类型的字符串值
js
typeof undefined === "undefined"; // true
typeof true === "boolean"; // true
typeof 42 === "number"; // true
typeof "42" === "string"; // true
typeof { life: 42 } === "object"; // true
// ES6中新加入的类型
typeof Symbol() === "symbol"; // true
神奇的null
- 正确的返回结果应该是 "null",但这个 bug 由来已久,在 JavaScript 中已经存在了将近二十年,也许永远也不会修复
js
typeof null === "object"; //true
判断null
js
var a = null;
const isNull = (!a && typeof a === "object");//true
console.log(isNull);
函数
- function 是 object的子类型
- 有一个内部属性
[[Call]]
,该属性使其可以被调用 - 还有其他属性,
length
表示参数的个数
js
console.log(typeof function () { } === "function");//true
function funa(a,b,c){}
console.log(funa.length);//3
数组
- 数组的类型是"object"
- 数组的length属性是元素的个数
js
console.log(typeof [1, 2, 3] === 'object');
1.3 值和类型
JavaScript 中的变量是没有类型的,只有值才有。变量可以随时持有任何类型的值。
在对变量执行 typeof 操作时,得到的结果并不是该变量的类型,而是该变量持有的值的类型,因为 JavaScript 中的变量没有类型。
js
var a = 42;
typeof a; // "number"
a = true;
typeof a; // "boolean"
1.3.1 undefined 和 undeclared
变量在未持有值的时候为 undefined。此时 typeof 返回 "undefined":
- 已在作用域中声明但还没有赋值的变量,是 undefined 的。
- 还没有在作用域中声明过的变量,是 undeclared 的。
- typeof 对于未定义和未声明的变量,都返回"undefined"
js
var a;
typeof a; // "undefined"
var b = 42;
var c;
// later
b = c;
typeof b; // "undefined"
typeof c; // "undefined"
//未声明的
d;//ReferenceError: b is not defined
//但是 typeof 处理的很特殊
typeof d;//"undefined"
1.3.2 typeof Undeclared
安全防范机制:确认是否有全局变量声明,而进行某些业务逻辑的处理
比如全局DEBUG标志
js
// 这样会抛出错误
if (DEBUG) {
console.log( "Debugging is starting" );
}
// 这样是安全的
if (typeof DEBUG !== "undefined") {
console.log( "Debugging is starting" );
}
比如用户自定义函数(polyfill
js
if (typeof atob === "undefined") {
atob = function() { /*..*/ };
}
其他的常见做法,检查window对象属性
js
if (window.DEBUG) {
// ..
}
if (!window.atob) {
// ..
}
检查外部函数是否存在,或使用默认实现
js
function doSomethingCool() {
var helper = (typeof FeatureXYZ !== "undefined") ? FeatureXYZ :function() { /*.. default feature ..*/ };
var val = helper();
// ..
}
或将依赖通过参数显式地传递到函数中
js
function doSomethingCool(FeatureXYZ) {
var helper = FeatureXYZ || function() { /*.. default feature ..*/ };
var val = helper();
// ..
}