简单的类型系统:
Number
(浮点数)String
Boolean
Date
Function
Array
Object
特殊类型:
NaN
null
undefined
typeof x
返回字符串,表示 x
的未经计算的数据类型。如:
typeof [1, 2, 3]
// 'object'
x instanceof t
返回布尔值,表示 x
是否从特定数据类型 t
的构造函数中创造。如:
const one = 1;
const str = "Hello World";
const b = true;
console.log(one instanceof Number);
console.log(str instanceof String);
console.log(b instanceof Boolean);
// 上面三个均为false
let x = 1 + 'hello'
// '1hello'
==
会进行类型转换;===
考虑数据类型也相等。推荐使用后者。
!=
、!==
同理。
let x = 0 == '';
// true
let x = 0 === '';
// false
a
为真,不代表 a == true
:
let a = 1
if(a) stmt // 执行 stmt
if(a == true) stmt // 不执行 stmt
字符串转数字(整数、浮点数):
parseInt(s)
parseFloat(s)
parseInt('100') // 100
parseInt('ABC') // NaN
parseInt('0xF') // 15
parseFloat('1.00') // 1
parseFloat('1.2') // 1.2
parseFloat('ABC') // NaN
parseInt('1.5') // 1
parseInt('1 + 1') // 1
parseInt(`${1 + 1}`) // 2
数字转字符串:
num.toString()