以下是一些常见的JavaScript代码片段,涵盖基础语法、函数、异步编程等主题:
基础语法
// 输出Hello World
console.log("Hello, World!");
// 变量声明
let message = "Hello";
const greeting = "Hi";
函数示例
// 函数定义
function add(a, b) {
return a + b;
}
// 箭头函数
const multiply = (x, y) => x * y;
异步编程
// Promise示例
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data));
// async/await
async function getData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
}
如需深入了解JavaScript基础概念,可访问JavaScript简介。