JavaScript 是一种动态类型、弱类型的脚本语言,支持多种编程范式(面向对象、函数式、命令式)。
let name = "John";
let Name = "Doe"; // 不同变量
_或$开头// 单行注释
/* 多行注释 */
// 分号可选,但推荐使用
let x = 1;
let y = 2;
// ES6 之前
var name = "张三"; // 函数作用域
// ES6 之后
let age = 25; // 块级作用域
const PI = 3.14; // 块级作用域,不可重新赋值
存储在栈中,直接存储值。
| 类型 | 说明 | 示例 |
|---|---|---|
undefined | 未定义(默认值) | let a; |
null | 空值(对象占位符) | let b = null; |
boolean | 布尔值 | true, false |
number | 数字(双精度浮点) | 42, 3.14, NaN, Infinity |
bigint | 大整数(ES2020) | 9007199254740991n |
string | 字符串 | "hello", 'world' |
symbol | 唯一值(ES2015) | Symbol('id') |
示例检查类型:
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (历史遗留问题)
typeof Symbol(); // "symbol"
typeof 100n; // "bigint"
存储在堆中,通过引用访问。
| 类型 | 说明 | 示例 |
|---|---|---|
Object | 通用对象 | { name: "John" } |
Array |
| 数组 |
[1, 2, 3] |
Function | 函数 | function() {} |
Date | 日期 | new Date() |
RegExp | 正则表达式 | /ab+c/ |
Map, Set | 集合(ES6) | new Map() |
| 其他内置对象 | Error, Promise 等 |
typeof {}; // "object"
typeof []; // "object" (使用 Array.isArray() 区分)
typeof function () {}; // "function"
// 更准确的检测
Array.isArray([]); // true
instanceof Array; // true
Object.prototype.toString.call([]); // "[object Array]"
// 变量类型可在运行时改变
let x = 10; // number
x = "hello"; // string
// 自动类型转换(隐式转换)
"5" + 3; // "53" (字符串拼接)
"5" - 2; // 3 (数字运算)
// 显式转换
Number("123"); // 123
String(123); // "123"
Boolean(1); // true
parseInt("10px"); // 10
parseFloat("3.14"); // 3.14
// 隐式转换
+"123"; // 123 (一元加)
!!"hello"; // true (双非)
NaN === NaN; // false (使用 isNaN() 或 Number.isNaN())
0 === -0; // true
Object.is(0, -0); // false (ES6)
let name = "John";
console.log(`Hello ${name}`); // Hello John
const [a, b] = [1, 2]; // a=1, b=2
const { name, age } = user;
const arr = [...[1, 2], 3]; // [1, 2, 3]
let value = null ?? "default"; // "default"
let value2 = 0 ?? "default"; // 0
let user = {};
let street = user?.address?.street; // undefined,不报错
typeofArray.isArray()null:value === nullObject.prototype.toString.call(value); // "[object Object]"
console.log(x); // undefined
var x = 5;
console.log(y); // ReferenceError
let y = 5;
"use strict";
// 启用严格模式,避免隐式全局变量等问题
// 松散相等(类型转换)
"5" == 5; // true
// 严格相等(推荐)
"5" === 5; // false
// Object.is (ES6)
Object.is(NaN, NaN); // true
Object.is(0, -0); // false
=== 而非 == 避免隐式转换const 声明常量,let 声明变量TypeScript 增强类型安全