字面量(Literals)是在代码中直接表示固定值的表示法。JavaScript 提供了多种类型的字面量。
// 十进制整数
42 - 10;
0;
// 浮点数
3.14;
0.5; // 0.5
5.0; // 5
// 科学计数法
1.23e4; // 12300
1.23e-4; // 0.000123
// 二进制(ES6+)
0b1010; // 10
0b1111; // 15
// 八进制(ES6+)
0o755; // 493
0o777; // 511
// 十六进制
0xff; // 255
0x1a3; // 419
// 单引号
"Hello World";
'It\'s a string'; // 转义
// 双引号
"Hello World";
'He said: "Hi!"'// 模板字面量(ES6+) // 转义
`Multiline
string``Hello ${name}!` // 插值表达式
`2 + 3 = ${2 + 3}`; // 计算表达式
// 标签模板
function tag(strings, ...values) {
return strings[0] + values[0];
}
tag(`Hello ${name}`);
true;
false;
null;
undefined; // 实际上是全局对象的属性,但通常视为字面量
/pattern/flags
// 示例
/ab+c/i
/^\d{3}-\d{4}$/
/\w+/g
// 基本对象
let obj = {
name: "张三",
age: 25,
isStudent: false,
};
// 计算属性名(ES6+)
let propName = "score";
let obj2 = {
[propName]: 95,
["exam" + "Date"]: "2024-01-01",
[Symbol.iterator]: function () {
/* ... */
},
};
// 方法简写
let obj3 = {
// ES5 方式
greet: function () {
return "Hello";
},
// ES6+ 简写
sayHi() {
return "Hi";
},
// 箭头函数(不推荐作为方法)
getName: () => this.name,
};
// Getter/Setter
let obj4 = {
_value: 0,
get value() {
return this._value;
},
set value(val) {
if (val >= 0) this._value = val;
},
};
// 基本数组
let arr = [1, 2, 3, 4, 5];
// 稀疏数组
let sparse = [1, , 3]; // 长度为3,中间为empty
// 嵌套数组
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
// 尾随逗号(ES5+)
let arr2 = [
"first",
"second", // 允许尾随逗号,不会有empty
];
// 函数表达式
let add = function (a, b) {
return a + b;
};
// 箭头函数(ES6+)
let multiply = (a, b) => a * b;
// 立即执行函数表达式(IIFE)
(function () {
console.log("立即执行");
})();
// 异步箭头函数
let fetchData = async () => {
let response = await fetch(url);
return response.json();
};
// BigInt 字面量
1234567890123456789012345678901234567890n;
// 与 Number 的转换
BigInt(123); // 123n
BigInt("123"); // 123n
// 不允许混合运算
let big = 100n;
// big + 50 // TypeError
// Symbol 创建(严格来说不是字面量,但类似)
let sym1 = Symbol();
let sym2 = Symbol("description");
// 全局 Symbol
let sym3 = Symbol.for("key");
// 内置 Symbol
Symbol.iterator;
Symbol.toStringTag;
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}`;
}
// 静态方法
static createAnonymous() {
return new Person("Anonymous");
}
// Getter/Setter
get fullName() {
return this.name;
}
set fullName(value) {
this.name = value;
}
}
let name = "张三";
let age = 25;
// ES5
let person1 = {
name: name,
age: age,
};
// ES6+ 简写
let person2 = {
name,
age,
};
// 对象解构
let { name, age: userAge } = { name: "张三", age: 25 };
// 数组解构
let [first, second] = [1, 2, 3];
// 默认值
let { x = 10, y = 20 } = { x: 5 };
// 嵌套解构
let {
a: { b },
} = { a: { b: 1 } };
let proto = { z: 3 };
let obj = {
// 原型链设置
__proto__: proto,
// 方法简写
method() {
return "hi";
},
// 计算属性名
["prop_" + (() => 42)()]: "computed",
};
// Infinity 和 -Infinity
Infinity - Infinity;
// NaN
NaN;
// 最大/最小安全整数
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MIN_SAFE_INTEGER; // -9007199254740991
// 最大/最小值
Number.MAX_VALUE; // 1.7976931348623157e+308
Number.MIN_VALUE; // 5e-324
function createElement(options = {}) {
let defaults = {
type: "div",
className: "",
text: "",
};
let config = { ...defaults, ...options };
// 使用 config...
}
// 交换变量
let a = 1,
b = 2;
[a, b] = [b, a];
// 获取剩余元素
let [first, ...rest] = [1, 2, 3, 4]; // rest = [2, 3, 4]
// 跳过元素
let [, second, , fourth] = [1, 2, 3, 4]; // second=2, fourth=4
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `<mark>${values[i]}</mark>` : "");
}, "");
}
let name = "张三";
let age = 25;
highlight(`姓名:${name},年龄:${age}`);
// 返回:姓名:<mark>张三</mark>,年龄:<mark>25</mark>
// ES5 严格模式:SyntaxError
let obj = {
x: 1,
x: 2, // 重复属性
};
// 旧语法(不推荐)
0777; // 511,某些环境下会解释为八进制
// ES6+ 标准
0o777; // 推荐使用
// 提高大数字的可读性
let billion = 1_000_000_000;
let bytes = 0b1010_0001_1000_0101;
let hex = 0xff_ff_ff;
// JSON(是字符串)
'{"name": "张三", "age": 25}'
// 对象字面量(是对象)
{name: "张三", age: 25}
// JSON 必须使用双引号,不能有方法、undefined等