以下是一些基础的 JavaScript 实例,涵盖了基本的语法、数据类型、控制流、函数、数组等常见的 JavaScript 特性:
1. 变量声明和数据类型
// 使用 var, let, const 声明变量
var name = "John"; // 字符串
let age = 25; // 数字
const isStudent = true; // 布尔值
// 打印变量
console.log(name); // 输出: John
console.log(age); // 输出: 25
console.log(isStudent); // 输出: true
// 数据类型
let number = 100; // Number
let str = "Hello, world!"; // String
let isActive = false; // Boolean
let user = null; // Null
let person = { // Object
name: "Alice",
age: 30
};
let numbers = [1, 2, 3, 4]; // Array
console.log(typeof number); // 输出: number
console.log(typeof str); // 输出: string
console.log(typeof isActive); // 输出: boolean
console.log(typeof person); // 输出: object
console.log(Array.isArray(numbers)); // 输出: true
2. 控制流:条件语句
let num = 10;
if (num > 0) {
console.log("Positive number");
} else if (num < 0) {
console.log("Negative number");
} else {
console.log("Zero");
}
// switch 语句
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
}
3. 循环:for, while
// for 循环
for (let i = 0; i < 5; i++) {
console.log(i); // 输出: 0, 1, 2, 3, 4
}
// while 循环
let count = 0;
while (count < 3) {
console.log(count); // 输出: 0, 1, 2
count++;
}
4. 函数定义和调用
// 函数定义
function greet(name) {
return "Hello, " + name + "!";
}
// 函数调用
console.log(greet("Alice")); // 输出: Hello, Alice!
// 匿名函数
const square = function(x) {
return x * x;
};
console.log(square(5)); // 输出: 25
// 箭头函数
const add = (a, b) => a + b;
console.log(add(3, 4)); // 输出: 7
5. 数组操作
// 创建数组
let fruits = ["apple", "banana", "cherry"];
// 访问数组元素
console.log(fruits[0]); // 输出: apple
// 添加元素
fruits.push("orange"); // 在末尾添加元素
fruits.unshift("grape"); // 在开头添加元素
// 删除元素
fruits.pop(); // 删除最后一个元素
fruits.shift(); // 删除第一个元素
// 遍历数组
fruits.forEach(function(fruit) {
console.log(fruit); // 输出: grape, apple, banana, cherry
});
6. 对象操作
// 创建对象
let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
// 访问对象属性
console.log(person.name); // 输出: John
console.log(person["age"]); // 输出: 30
// 调用对象方法
person.greet(); // 输出: Hello, John
7. 事件处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Event Example</title>
</head>
<body>
<button id="clickButton">Click Me</button>
<script>
// 获取按钮元素
const button = document.getElementById("clickButton");
// 添加点击事件监听器
button.addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
8. 异步操作:setTimeout 和 setInterval
// setTimeout:延迟执行代码
setTimeout(function() {
console.log("This message appears after 2 seconds");
}, 2000);
// setInterval:每隔一段时间执行代码
let counter = 0;
const interval = setInterval(function() {
counter++;
console.log("Counter: " + counter);
if (counter === 5) {
clearInterval(interval); // 停止计时器
}
}, 1000); // 每隔 1 秒执行一次
9. JSON 操作
// JSON.stringify:将对象转换为 JSON 字符串
let person = {
name: "Alice",
age: 25
};
let jsonString = JSON.stringify(person);
console.log(jsonString); // 输出: '{"name":"Alice","age":25}'
// JSON.parse:将 JSON 字符串解析为对象
let parsedPerson = JSON.parse(jsonString);
console.log(parsedPerson.name); // 输出: Alice
10. 错误处理:try…catch
try {
let result = 10 / 0; // Infinity
console.log(result);
throw new Error("Something went wrong");
} catch (error) {
console.error("Caught an error: " + error.message); // 输出: Caught an error: Something went wrong
} finally {
console.log("This block always runs");
}
总结
这些是 JavaScript 中常见的基础实例,涵盖了变量、数据类型、控制流、函数、数组、对象、事件等常用操作。通过这些例子,你可以更好地理解和应用 JavaScript 来实现动态交互和功能。
发表回复