记录学习 JavaScript 时整理的基础语法,方便复习。
let count = 0; // 可重新赋值
const name = "Tom"; // 常量,不可重新赋值
// 尽量避免使用 var
基本类型:string、number、boolean、null、undefined、symbol、bigint;其余为对象(包括数组和函数)。
typeof 42 // "number"
typeof "hi" // "string"
Array.isArray([]) // true
function add(a, b) {
return a + b;
}
const mul = (a, b) => a * b; // 箭头函数
const nums = [1, 2, 3, 4];
nums.map(n => n * 2); // [2, 4, 6, 8]
nums.filter(n => n % 2 === 0); // [2, 4]
nums.reduce((s, n) => s + n, 0); // 10
const user = { name: "Tom", age: 20 };
const { name, age } = user;
const copy = { ...user, age: 21 };
const el = document.querySelector("#title");
el.textContent = "新的标题";
el.addEventListener("click", () => {
console.log("被点击了");
});
尽量使用 === 而不是 ==,后者会做隐式类型转换,容易产生意料之外的结果。