 | |  |  | JavaScript语法小示例
- // JavaScript 高级功能综合示例
- // 基于 AIWROK 软件技术文档中的 JavaScript 语句说明
- // 包含基础概念和高级功能的完整演示
- // ==================== 第一部分:基础概念 ====================
- console.log("\n========== JavaScript 基础概念演示开始 ==========");
- sleep.second(秒=2);
- // 1. JavaScript 语句 - 用分号分隔的命令
- console.log("\n【1】JavaScript 语句示例");
- var x = 5 + 6; // 数字运算
- var y = x * 10; // 表达式计算
- console.log("x = " + x + ", y = " + y);
- sleep.second(秒=2);
- // 2. JavaScript 关键字使用示例
- console.log("\n【2】JavaScript 关键字使用示例");
- var firstName = "John"; // var 关键字声明变量
- var lastName = "Doe"; // 字符串赋值
- var age = 30; // 数字赋值
- var isActive = true; // 布尔值
- console.log("姓名: " + firstName + " " + lastName + ", 年龄: " + age + ", 激活状态: " + isActive);
- sleep.second(秒=2);
- // 3. JavaScript 注释示例
- // 这是单行注释,不会被执行
- /*
- 这是多行注释
- 也不会被执行
- */
- // 4. JavaScript 数据类型示例
- console.log("\n【4】JavaScript 数据类型示例");
- var length = 16; // Number 类型
- var points = x * 10; // Number 通过表达式
- var fullName = firstName + " " + lastName; // String 字符串拼接
- var hobbies = ["阅读", "编程", "运动"]; // Array 数组
- var person = { // Object 对象
- firstName: firstName,
- lastName: lastName,
- age: age,
- isActive: isActive
- };
- console.log("长度: " + length + ", 分数: " + points);
- console.log("全名: " + fullName);
- console.log("爱好数量: " + hobbies.length);
- sleep.second(秒=2);
- // 5. 数据类型操作示例
- console.log("\n【5】数据类型操作示例");
- var numStr = 16 + "Volvo"; // 数字与字符串拼接结果为 "16Volvo"
- console.log("数字与字符串拼接结果: " + numStr);
- sleep.second(秒=2);
- // 6. JavaScript 函数示例
- console.log("\n【6】JavaScript 函数示例");
- function calculateArea(width, height) {
- return width * height; // 返回面积计算结果
- }
- function greetUser(name) {
- return "你好, " + name + "!"; // 返回问候语
- }
- // 调用函数
- var area = calculateArea(5, 10);
- var greeting = greetUser(firstName);
- console.log("矩形面积 (5x10): " + area);
- console.log(greeting);
- sleep.second(秒=2);
- // 7. 大小写敏感性示例
- console.log("\n【7】大小写敏感性示例");
- var myVariable = "小写变量";
- var MyVariable = "大写开头变量";
- // 注意:myVariable 和 MyVariable 是两个不同的变量
- console.log("myVariable: " + myVariable);
- console.log("MyVariable: " + MyVariable);
- console.log("两个变量不同: " + (myVariable !== MyVariable));
- sleep.second(秒=2);
- // 8. 更多关键字使用示例
- console.log("\n【8】控制流关键字示例");
- if (age >= 18) {
- console.log("年龄 " + age + " - 成年人");
- } else {
- console.log("年龄 " + age + " - 未成年人");
- }
- console.log("\n遍历爱好列表:");
- for (var i = 0; i < hobbies.length; i++) {
- console.log(" 爱好 " + (i+1) + ": " + hobbies[i]);
- }
- sleep.second(秒=2);
- // 9. switch 语句示例
- console.log("\n【9】switch 语句示例");
- var day = 3;
- var dayName;
- switch (day) {
- case 1:
- dayName = "星期一";
- break;
- case 2:
- dayName = "星期二";
- break;
- case 3:
- dayName = "星期三";
- break;
- default:
- dayName = "其他日期";
- }
- console.log("今天是: " + dayName);
- sleep.second(秒=2);
- // 10. try-catch 错误处理示例
- console.log("\n【10】try-catch 错误处理示例");
- try {
- var result = undefinedVariable + 10; // 这会引发错误
- } catch (error) {
- console.log("捕获到错误: " + error.message);
- console.log("错误处理成功!");
- }
- sleep.second(秒=2);
- // 11. 数组操作方法
- console.log("\n【11】数组操作方法示例");
- var numbers = [1, 2, 3, 4, 5];
- console.log("原始数组: " + numbers.join(", "));
- numbers.push(6); // 添加元素
- console.log("push后: " + numbers.join(", "));
- numbers.pop(); // 移除最后一个元素
- console.log("pop后: " + numbers.join(", "));
- sleep.second(秒=2);
- // 12. 对象方法示例
- console.log("\n【12】对象方法示例");
- person.getFullName = function() {
- return this.firstName + " " + this.lastName;
- };
- console.log("完整姓名: " + person.getFullName());
- console.log("人员信息: " + JSON.stringify(person));
- sleep.second(秒=2);
- // ==================== 第二部分:高级功能 ====================
- console.log("\n========== JavaScript 高级功能演示开始 ==========");
- sleep.second(秒=2);
- // 13. 闭包示例
- console.log("\n【13】闭包示例");
- function createCounter() {
- var count = 0;
- return {
- increment: function() {
- count++;
- return count;
- },
- decrement: function() {
- count--;
- return count;
- },
- getCount: function() {
- return count;
- }
- };
- }
- var counter = createCounter();
- console.log("计数器初始值: " + counter.getCount());
- console.log("递增后: " + counter.increment());
- console.log("再递增: " + counter.increment());
- console.log("递减后: " + counter.decrement());
- sleep.second(秒=2);
- // 14. 递归函数示例
- console.log("\n【14】递归函数示例");
- function factorial(n) {
- if (n <= 1) return 1;
- return n * factorial(n - 1);
- }
- console.log("5的阶乘: " + factorial(5));
- console.log("10的阶乘: " + factorial(10));
- sleep.second(秒=2);
- // 15. 高阶函数示例
- console.log("\n【15】高阶函数示例");
- function applyOperation(arr, operation) {
- var result = [];
- for (var i = 0; i < arr.length; i++) {
- result.push(operation(arr[i]));
- }
- return result;
- }
- var squaredNumbers = applyOperation([1, 2, 3, 4, 5], function(num) {
- return num * num;
- });
- console.log("原始数组: [1, 2, 3, 4, 5]");
- console.log("平方数组: " + squaredNumbers.join(", "));
- sleep.second(秒=2);
- // 16. 原型链示例
- console.log("\n【16】原型链继承示例");
- function Animal(name, type) {
- this.name = name;
- this.type = type;
- }
- Animal.prototype.speak = function() {
- return this.name + " 发出了声音";
- };
- function Dog(name) {
- Animal.call(this, name, "狗");
- }
- Dog.prototype = Object.create(Animal.prototype);
- Dog.prototype.constructor = Dog;
- Dog.prototype.bark = function() {
- return this.name + " 汪汪叫";
- };
- var myDog = new Dog("旺财");
- console.log(myDog.speak());
- console.log(myDog.bark());
- sleep.second(秒=2);
- // 17. Promise 模拟(由于环境限制,使用回调方式)
- console.log("\n【17】异步编程示例");
- function asyncOperation(data, callback) {
- setTimeout(function() {
- var result = "处理完成: " + data;
- callback(null, result);
- }, 100);
- }
- asyncOperation("测试数据", function(error, result) {
- if (error) {
- console.log("错误: " + error);
- } else {
- console.log(result);
- }
- });
- sleep.second(秒=2);
- // 18. 模块化模式
- console.log("\n【18】模块化模式示例");
- var MathUtils = (function() {
- // 私有变量和方法
- var PI = 3.14159265359;
-
- function validateNumber(num) {
- return typeof num === 'number' && !isNaN(num);
- }
-
- // 公共API
- return {
- circleArea: function(radius) {
- if (!validateNumber(radius) || radius < 0) {
- throw new Error("无效的半径值");
- }
- return PI * radius * radius;
- },
- rectangleArea: function(width, height) {
- if (!validateNumber(width) || !validateNumber(height)) {
- throw new Error("无效的尺寸值");
- }
- return width * height;
- },
- add: function(a, b) {
- if (!validateNumber(a) || !validateNumber(b)) {
- throw new Error("无效的数字参数");
- }
- return a + b;
- }
- };
- })();
- console.log("圆面积 (r=5): " + MathUtils.circleArea(5));
- console.log("矩形面积 (5x10): " + MathUtils.rectangleArea(5, 10));
- console.log("加法 (3+7): " + MathUtils.add(3, 7));
- sleep.second(秒=2);
- // 19. 事件模拟器
- console.log("\n【19】事件系统示例");
- var EventEmitter = function() {
- this.events = {};
- };
- EventEmitter.prototype.on = function(event, listener) {
- if (!this.events[event]) {
- this.events[event] = [];
- }
- this.events[event].push(listener);
- };
- EventEmitter.prototype.emit = function(event) {
- if (this.events[event]) {
- var args = Array.prototype.slice.call(arguments, 1);
- this.events[event].forEach(function(listener) {
- listener.apply(null, args);
- });
- }
- };
- var emitter = new EventEmitter();
- emitter.on('greet', function(name) {
- console.log("欢迎, " + name + "!");
- });
- emitter.on('data', function(data) {
- console.log("收到数据: " + data);
- });
- emitter.emit('greet', '用户');
- emitter.emit('data', '重要信息');
- sleep.second(秒=2);
- // 20. 数据结构实现 - 栈
- console.log("\n【20】栈 (Stack) 数据结构示例");
- function Stack() {
- this.items = [];
- }
- Stack.prototype.push = function(item) {
- this.items.push(item);
- };
- Stack.prototype.pop = function() {
- if (this.isEmpty()) {
- return null;
- }
- return this.items.pop();
- };
- Stack.prototype.peek = function() {
- if (this.isEmpty()) {
- return null;
- }
- return this.items[this.items.length - 1];
- };
- Stack.prototype.isEmpty = function() {
- return this.items.length === 0;
- };
- Stack.prototype.size = function() {
- return this.items.length;
- };
- var stack = new Stack();
- stack.push(1);
- stack.push(2);
- stack.push(3);
- console.log("栈顶元素: " + stack.peek());
- console.log("弹出元素: " + stack.pop());
- console.log("栈大小: " + stack.size());
- sleep.second(秒=2);
- // 21. 数据结构实现 - 队列
- console.log("\n【21】队列 (Queue) 数据结构示例");
- function Queue() {
- this.items = [];
- }
- Queue.prototype.enqueue = function(item) {
- this.items.push(item);
- };
- Queue.prototype.dequeue = function() {
- if (this.isEmpty()) {
- return null;
- }
- return this.items.shift();
- };
- Queue.prototype.front = function() {
- if (this.isEmpty()) {
- return null;
- }
- return this.items[0];
- };
- Queue.prototype.isEmpty = function() {
- return this.items.length === 0;
- };
- Queue.prototype.size = function() {
- return this.items.length;
- };
- var queue = new Queue();
- queue.enqueue("任务1");
- queue.enqueue("任务2");
- queue.enqueue("任务3");
- console.log("队首任务: " + queue.front());
- console.log("完成任务: " + queue.dequeue());
- console.log("剩余任务数: " + queue.size());
- sleep.second(秒=2);
- // 22. 正则表达式示例
- console.log("\n【22】正则表达式验证示例");
- function validateEmail(email) {
- var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
- return emailRegex.test(email);
- }
- function validatePhone(phone) {
- var phoneRegex = /^1[3-9]\d{9}$/;
- return phoneRegex.test(phone);
- }
- console.log("邮箱验证 test@example.com: " + validateEmail("test@example.com"));
- console.log("手机号验证 13812345678: " + validatePhone("13812345678"));
- sleep.second(秒=2);
- // 23. JSON 操作示例
- console.log("\n【23】JSON 数据处理示例");
- var userData = {
- id: 1,
- name: "张三",
- age: 25,
- hobbies: ["读书", "游泳"],
- address: {
- city: "北京",
- street: "长安街100号"
- }
- };
- var jsonString = JSON.stringify(userData);
- console.log("JSON字符串: " + jsonString);
- var parsedData = JSON.parse(jsonString);
- console.log("解析后的名字: " + parsedData.name);
- console.log("解析后的城市: " + parsedData.address.city);
- sleep.second(秒=2);
- // 24. 字符串处理方法
- console.log("\n【24】字符串处理方法示例");
- var text = "Hello World JavaScript";
- console.log("转大写: " + text.toUpperCase());
- console.log("转小写: " + text.toLowerCase());
- console.log("子字符串: " + text.substring(0, 5));
- console.log("替换: " + text.replace("World", "宇宙"));
- console.log("分割: " + text.split(" ").join("-"));
- sleep.second(秒=2);
- // 25. 日期和时间处理
- console.log("\n【25】日期和时间处理示例");
- var now = new Date();
- console.log("当前时间: " + now.toLocaleString());
- console.log("年份: " + now.getFullYear());
- console.log("月份: " + (now.getMonth() + 1));
- console.log("日期: " + now.getDate());
- console.log("小时: " + now.getHours());
- console.log("分钟: " + now.getMinutes());
- console.log("秒数: " + now.getSeconds());
- sleep.second(秒=2);
- // 26. Map 数据结构
- console.log("\n【26】Map 数据结构示例");
- function CustomMap() {
- this.keys = [];
- this.values = [];
- }
- CustomMap.prototype.set = function(key, value) {
- var index = this.keys.indexOf(key);
- if (index !== -1) {
- this.values[index] = value;
- } else {
- this.keys.push(key);
- this.values.push(value);
- }
- };
- CustomMap.prototype.get = function(key) {
- var index = this.keys.indexOf(key);
- if (index !== -1) {
- return this.values[index];
- }
- return undefined;
- };
- CustomMap.prototype.has = function(key) {
- return this.keys.indexOf(key) !== -1;
- };
- CustomMap.prototype.delete = function(key) {
- var index = this.keys.indexOf(key);
- if (index !== -1) {
- this.keys.splice(index, 1);
- this.values.splice(index, 1);
- return true;
- }
- return false;
- };
- CustomMap.prototype.size = function() {
- return this.keys.length;
- };
- var map = new CustomMap();
- map.set("name", "李四");
- map.set("age", 28);
- map.set("city", "上海");
- console.log("Map中获取name: " + map.get("name"));
- console.log("Map中是否存在age: " + map.has("age"));
- console.log("Map大小: " + map.size());
- map.delete("city");
- console.log("删除city后Map大小: " + map.size());
- sleep.second(秒=2);
- // 27. Set 数据结构
- console.log("\n【27】Set 数据结构示例");
- function CustomSet() {
- this.items = {};
- }
- CustomSet.prototype.add = function(value) {
- this.items[value] = value;
- };
- CustomSet.prototype.has = function(value) {
- return this.items.hasOwnProperty(value);
- };
- CustomSet.prototype.delete = function(value) {
- if (this.has(value)) {
- delete this.items[value];
- return true;
- }
- return false;
- };
- CustomSet.prototype.size = function() {
- return Object.keys(this.items).length;
- };
- CustomSet.prototype.values = function() {
- return Object.keys(this.items);
- };
- var set = new CustomSet();
- set.add(1);
- set.add(2);
- set.add(3);
- set.add(2); // 重复值不会添加
- console.log("Set中的值: " + set.values().join(", "));
- console.log("Set大小: " + set.size());
- console.log("是否包含2: " + set.has(2));
- set.delete(1);
- console.log("删除1后Set大小: " + set.size());
- sleep.second(秒=2);
- // 28. 观察者模式
- console.log("\n【28】观察者模式示例");
- function Subject() {
- this.observers = [];
- }
- Subject.prototype.addObserver = function(observer) {
- this.observers.push(observer);
- };
- Subject.prototype.removeObserver = function(observer) {
- var index = this.observers.indexOf(observer);
- if (index > -1) {
- this.observers.splice(index, 1);
- }
- };
- Subject.prototype.notify = function(data) {
- this.observers.forEach(function(observer) {
- observer.update(data);
- });
- };
- function Observer(name) {
- this.name = name;
- }
- Observer.prototype.update = function(data) {
- console.log(this.name + " 收到更新: " + data);
- };
- var subject = new Subject();
- var observer1 = new Observer("观察者1");
- var observer2 = new Observer("观察者2");
- subject.addObserver(observer1);
- subject.addObserver(observer2);
- subject.notify("状态改变");
- sleep.second(秒=2);
- // 29. 工厂模式
- console.log("\n【29】工厂模式示例");
- function createUser(type, name, age) {
- var user = {
- name: name,
- age: age,
- type: type
- };
-
- if (type === "admin") {
- user.permissions = ["read", "write", "delete"];
- } else if (type === "user") {
- user.permissions = ["read"];
- }
-
- user.getInfo = function() {
- return this.name + " (" + this.type + "), 年龄: " + this.age;
- };
-
- return user;
- }
- var admin = createUser("admin", "管理员", 35);
- var regularUser = createUser("user", "普通用户", 25);
- console.log(admin.getInfo());
- console.log("管理员权限: " + admin.permissions.join(", "));
- console.log(regularUser.getInfo());
- console.log("普通用户权限: " + regularUser.permissions.join(", "));
- sleep.second(秒=2);
- // 30. 装饰器模式
- console.log("\n【30】装饰器模式示例");
- function Coffee(price) {
- this.price = price;
- }
- Coffee.prototype.cost = function() {
- return this.price;
- };
- function MilkDecorator(coffee) {
- this.coffee = coffee;
- }
- MilkDecorator.prototype.cost = function() {
- return this.coffee.cost() + 5;
- };
- function SugarDecorator(coffee) {
- this.coffee = coffee;
- }
- SugarDecorator.prototype.cost = function() {
- return this.coffee.cost() + 2;
- };
- var basicCoffee = new Coffee(10);
- var milkCoffee = new MilkDecorator(basicCoffee);
- var sweetMilkCoffee = new SugarDecorator(milkCoffee);
- console.log("基础咖啡价格: " + basicCoffee.cost());
- console.log("加奶咖啡价格: " + milkCoffee.cost());
- console.log("加糖加奶咖啡价格: " + sweetMilkCoffee.cost());
- sleep.second(秒=2);
- // 输出所有示例结果总结
- console.log("\n========== JavaScript 演示完成 ==========");
- console.log("\n已演示以下功能:");
- console.log("1. 基础语法和数据类型");
- console.log("2. 函数和闭包");
- console.log("3. 面向对象编程");
- console.log("4. 异步编程模式");
- console.log("5. 模块化设计");
- console.log("6. 事件系统");
- console.log("7. 数据结构实现 (栈、队列、Map、Set)");
- console.log("8. 正则表达式");
- console.log("9. JSON处理");
- console.log("10. 字符串和日期处理");
- console.log("11. 设计模式应用 (工厂、观察者、装饰器)");
- console.log("\n总计: 30个功能模块演示完成!");
- console.log("\n========== 演示结束 ==========");
复制代码
| |  | |  |
|