1. JavaScript简介
JavaScript是Web开发的三大核心技术之一(HTML、CSS、JavaScript),它让网页具有交互性。使用我们的JS在线编辑器可以实时运行JavaScript代码。
2. 变量声明:var、let、const
// var - 函数作用域 (不推荐使用)
var name = "HTML编辑器";
// let - 块级作用域,可重新赋值
let count = 0;
count = 1; // ✅
// const - 块级作用域,常量
const PI = 3.14159;
// PI = 3; // ❌ 报错
3. 数据类型
JavaScript有7种基本数据类型:undefined、null、boolean、number、string、symbol、bigint,以及引用类型object。
// 类型检测
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (历史遗留bug)
typeof {} // "object"
typeof [] // "object"
4. 作用域与闭包
闭包是指有权访问另一个函数作用域中变量的函数。它是JavaScript最强大的特性之一:
function createCounter() {
let count = 0; // 闭包变量
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
5. 异步编程
// Promise
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// async/await (更简洁)
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}