 | |  |  | 安卓脚本AIWROK软件示例JS函数高级用法
- // AIWROK 软件 - JavaScript函数综合示例大全
- // 作者: AIWROK 开发团队
- // 日期: 2024年6月
- // 🍎交流QQ群711841924群一,苹果内测群,528816639
- /**
- * =============================================================================
- * JavaScript函数综合示例大全
- * =============================================================================
- * 基于主脚本中的函数语法说明,展示JavaScript函数的各种高级应用
- * 包含:基础函数、闭包、高阶函数、递归、设计模式、异步编程、性能优化、错误处理
- *
- * 兼容性:Rhino 引擎 (ES5)
- * 平台:AIWROK 安卓自动化软件
- * =============================================================================
- */
- // =============================================================================
- // 工具函数
- // =============================================================================
- // 延迟函数(避免与系统sleep冲突)
- function delay(ms) {
- var start = new Date().getTime();
- while (new Date().getTime() < start + ms) {
- // 等待
- }
- }
- // =============================================================================
- // 第一部分:基础函数示例
- // =============================================================================
- // 简单函数定义
- function greet(name) {
- return "你好, " + name + "!";
- }
- // 带默认参数的函数
- function greetWithDefault(name) {
- var defaultName = "用户";
- if (name === undefined || name === null) {
- name = defaultName;
- }
- return "你好, " + name + "!";
- }
- // 多参数函数
- function calculateArea(width, height) {
- return width * height;
- }
- // 演示基础函数
- function demoBasicFunctions() {
- console.log("=== 基础函数示例 ===");
-
- var greeting = greet("张三");
- console.log(greeting);
-
- var defaultGreeting = greetWithDefault();
- console.log(defaultGreeting);
-
- var area = calculateArea(5, 10);
- console.log("矩形面积: " + area);
- }
- // =============================================================================
- // 第二部分:返回值与条件返回
- // =============================================================================
- // 返回单个值
- function getMaxValue(arr) {
- if (!arr || arr.length === 0) {
- return null;
- }
-
- var max = arr[0];
- for (var i = 1; i < arr.length; i++) {
- if (arr[i] > max) {
- max = arr[i];
- }
- }
- return max;
- }
- // 条件返回示例
- function divideNumbers(a, b) {
- if (b === 0) {
- return "错误: 除数不能为零";
- }
- return a / b;
- }
- // 演示返回值函数
- function demoReturnValues() {
- console.log("=== 返回值函数示例 ===");
-
- var numbers = [3, 7, 2, 9, 1, 5];
- var maxValue = getMaxValue(numbers);
- console.log("数组最大值: " + maxValue);
-
- var result1 = divideNumbers(10, 2);
- console.log("10 ÷ 2 = " + result1);
-
- var result2 = divideNumbers(10, 0);
- console.log(result2);
- }
- // =============================================================================
- // 第三部分:闭包与私有变量
- // =============================================================================
- // 创建计数器工厂函数
- function createCounter(initialValue) {
- var count = initialValue || 0;
-
- return {
- increment: function() {
- count++;
- return count;
- },
- decrement: function() {
- count--;
- return count;
- },
- getValue: function() {
- return count;
- },
- reset: function() {
- count = initialValue || 0;
- return count;
- }
- };
- }
- // 演示闭包
- function demoClosures() {
- console.log("=== 闭包示例 ===");
-
- var counter1 = createCounter(0);
- var counter2 = createCounter(10);
-
- console.log("计数器1初始值: " + counter1.getValue());
- console.log("计数器2初始值: " + counter2.getValue());
-
- counter1.increment();
- counter1.increment();
- counter2.decrement();
-
- console.log("计数器1当前值: " + counter1.getValue());
- console.log("计数器2当前值: " + counter2.getValue());
- }
- // =============================================================================
- // 第四部分:高阶函数
- // =============================================================================
- // 高阶函数:接收函数作为参数
- function applyOperation(a, b, operation) {
- return operation(a, b);
- }
- function add(a, b) { return a + b; }
- function subtract(a, b) { return a - b; }
- function multiply(a, b) { return a * b; }
- // 高阶函数:返回函数
- function createMultiplier(factor) {
- return function(number) {
- return number * factor;
- };
- }
- // 演示高阶函数
- function demoHigherOrderFunctions() {
- console.log("=== 高阶函数示例 ===");
-
- var sum = applyOperation(5, 3, add);
- console.log("5 + 3 = " + sum);
-
- var product = applyOperation(6, 7, multiply);
- console.log("6 × 7 = " + product);
-
- var double = createMultiplier(2);
- console.log("5 的两倍: " + double(5));
- }
- // =============================================================================
- // 第五部分:递归函数
- // =============================================================================
- // 计算阶乘
- function factorial(n) {
- if (n <= 1) {
- return 1;
- }
- return n * factorial(n - 1);
- }
- // 斐波那契数列
- function fibonacci(n) {
- if (n <= 1) {
- return n;
- }
- return fibonacci(n - 1) + fibonacci(n - 2);
- }
- // 演示递归函数
- function demoRecursion() {
- console.log("=== 递归函数示例 ===");
-
- console.log("5! = " + factorial(5));
- console.log("7! = " + factorial(7));
-
- console.log("斐波那契数列前10项:");
- for (var i = 0; i < 10; i++) {
- console.log("F(" + i + ") = " + fibonacci(i));
- }
- }
- // =============================================================================
- // 第六部分:构造函数与面向对象
- // =============================================================================
- // 定义学生类
- function Student(name, age, grade) {
- this.name = name;
- this.age = age;
- this.grade = grade;
-
- this.getInfo = function() {
- return "姓名: " + this.name + ", 年龄: " + this.age + ", 年级: " + this.grade;
- };
-
- this.isAdult = function() {
- return this.age >= 18;
- };
- }
- Student.prototype.promote = function() {
- this.grade++;
- return this.grade;
- };
- // 演示构造函数
- function demoConstructors() {
- console.log("=== 构造函数示例 ===");
-
- var student1 = new Student("张三", 16, 10);
- var student2 = new Student("李四", 19, 12);
-
- console.log(student1.getInfo());
- console.log("是否成年: " + student1.isAdult());
-
- student1.promote();
- console.log(student1.name + " 升级到年级: " + student1.grade);
- }
- // =============================================================================
- // 第七部分:回调函数
- // =============================================================================
- // 模拟异步操作
- function simulateAsyncOperation(data, callback) {
- var processedData = data.toUpperCase();
- callback(processedData);
- }
- // 处理数组的每个元素
- function processArray(arr, processor) {
- var results = [];
- for (var i = 0; i < arr.length; i++) {
- results.push(processor(arr[i]));
- }
- return results;
- }
- // 演示回调函数
- function demoCallbacks() {
- console.log("=== 回调函数示例 ===");
-
- simulateAsyncOperation("hello world", function(result) {
- console.log("异步操作结果: " + result);
- });
-
- var numbers = [1, 2, 3, 4, 5];
- var squared = processArray(numbers, function(num) {
- return num * num;
- });
- console.log("平方结果: " + JSON.stringify(squared));
- }
- // =============================================================================
- // 第八部分:单例模式
- // =============================================================================
- var ConfigManager = (function() {
- var instance;
-
- function ConfigManager() {
- this.config = {};
-
- this.set = function(key, value) {
- this.config[key] = value;
- };
-
- this.get = function(key) {
- return this.config[key];
- };
- }
-
- return {
- getInstance: function() {
- if (!instance) {
- instance = new ConfigManager();
- }
- return instance;
- }
- };
- })();
- // 演示单例模式
- function demoSingletonPattern() {
- console.log("=== 单例模式示例 ===");
-
- var config1 = ConfigManager.getInstance();
- var config2 = ConfigManager.getInstance();
-
- console.log("两个实例是否相同: " + (config1 === config2));
-
- config1.set("appName", "AIWROK");
- config1.set("version", "2.0");
-
- console.log("应用名称: " + config2.get("appName"));
- console.log("版本号: " + config2.get("version"));
- }
- // =============================================================================
- // 第九部分:工厂模式
- // =============================================================================
- // 形状基类
- function Shape(type) {
- this.type = type;
- }
- Shape.prototype.draw = function() {
- throw new Error("draw方法必须被重写");
- };
- // 圆形类
- function Circle(radius) {
- Shape.call(this, "circle");
- this.radius = radius;
- }
- Circle.prototype = Object.create(Shape.prototype);
- Circle.prototype.constructor = Circle;
- Circle.prototype.draw = function() {
- return "绘制圆形,半径: " + this.radius;
- };
- // 矩形类
- function Rectangle(width, height) {
- Shape.call(this, "rectangle");
- this.width = width;
- this.height = height;
- }
- Rectangle.prototype = Object.create(Shape.prototype);
- Rectangle.prototype.constructor = Rectangle;
- Rectangle.prototype.draw = function() {
- return "绘制矩形,宽: " + this.width + ", 高: " + this.height;
- };
- // 形状工厂
- function ShapeFactory() {
- this.createShape = function(type, params) {
- switch (type.toLowerCase()) {
- case "circle":
- return new Circle(params.radius || 1);
- case "rectangle":
- return new Rectangle(params.width || 1, params.height || 1);
- default:
- throw new Error("不支持的形状类型: " + type);
- }
- };
- }
- // 演示工厂模式
- function demoFactoryPattern() {
- console.log("=== 工厂模式示例 ===");
-
- var factory = new ShapeFactory();
-
- var circle = factory.createShape("circle", { radius: 5 });
- var rectangle = factory.createShape("rectangle", { width: 4, height: 6 });
-
- console.log(circle.draw());
- console.log(rectangle.draw());
- }
- // =============================================================================
- // 第十部分:观察者模式
- // =============================================================================
- function EventEmitter() {
- this.events = {};
- }
- EventEmitter.prototype.on = function(eventName, listener) {
- if (!this.events[eventName]) {
- this.events[eventName] = [];
- }
- this.events[eventName].push(listener);
- };
- EventEmitter.prototype.emit = function(eventName) {
- var args = Array.prototype.slice.call(arguments, 1);
-
- if (this.events[eventName]) {
- for (var i = 0; i < this.events[eventName].length; i++) {
- this.events[eventName][i].apply(null, args);
- }
- }
- };
- // 演示观察者模式
- function demoObserverPattern() {
- console.log("=== 观察者模式示例 ===");
-
- var emitter = new EventEmitter();
-
- var listener1 = function(data) {
- console.log("监听器1收到: " + data);
- };
-
- var listener2 = function(data) {
- console.log("监听器2收到: " + data);
- };
-
- emitter.on("data", listener1);
- emitter.on("data", listener2);
-
- console.log("触发data事件:");
- emitter.emit("data", "第一条数据");
- }
- // =============================================================================
- // 第十一部分:Promise模拟
- // =============================================================================
- function SimplePromise(executor) {
- this.state = "pending";
- this.value = null;
- this.callbacks = [];
-
- var self = this;
-
- function resolve(value) {
- if (self.state === "pending") {
- self.state = "fulfilled";
- self.value = value;
-
- setTimeout(function() {
- for (var i = 0; i < self.callbacks.length; i++) {
- self.callbacks[i].onFulfilled(value);
- }
- }, 0);
- }
- }
-
- function reject(reason) {
- if (self.state === "pending") {
- self.state = "rejected";
- self.value = reason;
-
- setTimeout(function() {
- for (var i = 0; i < self.callbacks.length; i++) {
- if (self.callbacks[i].onRejected) {
- self.callbacks[i].onRejected(reason);
- }
- }
- }, 0);
- }
- }
-
- try {
- executor(resolve, reject);
- } catch (e) {
- reject(e);
- }
- }
- SimplePromise.prototype.then = function(onFulfilled, onRejected) {
- var self = this;
-
- return new SimplePromise(function(resolve, reject) {
- function handleValue(value) {
- try {
- if (typeof onFulfilled === "function") {
- var result = onFulfilled(value);
- resolve(result);
- } else {
- resolve(value);
- }
- } catch (e) {
- reject(e);
- }
- }
-
- if (self.state === "fulfilled") {
- setTimeout(function() {
- handleValue(self.value);
- }, 0);
- } else {
- self.callbacks.push({
- onFulfilled: handleValue,
- onRejected: onRejected
- });
- }
- });
- };
- // 演示Promise
- function demoPromise() {
- console.log("=== Promise示例 ===");
-
- var promise1 = new SimplePromise(function(resolve, reject) {
- setTimeout(function() {
- resolve("Promise完成");
- }, 100);
- });
-
- promise1.then(function(result) {
- console.log("结果: " + result);
- });
- }
- // =============================================================================
- // 第十二部分:记忆化优化
- // =============================================================================
- function memoize(func) {
- var cache = {};
-
- return function() {
- var key = JSON.stringify(arguments);
-
- if (cache.hasOwnProperty(key)) {
- return cache[key];
- }
-
- var result = func.apply(this, arguments);
- cache[key] = result;
- return result;
- };
- }
- // 记忆化斐波那契
- var fibonacciMemoized = memoize(function(n) {
- if (n <= 1) return n;
- return fibonacciMemoized(n - 1) + fibonacciMemoized(n - 2);
- });
- // 演示记忆化
- function demoMemoization() {
- console.log("=== 记忆化示例 ===");
-
- var start1 = new Date().getTime();
- var result1 = fibonacciMemoized(30);
- var time1 = new Date().getTime() - start1;
- console.log("记忆化斐波那契(30): " + result1 + ", 耗时: " + time1 + "ms");
-
- var start2 = new Date().getTime();
- var result2 = fibonacciMemoized(30);
- var time2 = new Date().getTime() - start2;
- console.log("再次调用(缓存): " + result2 + ", 耗时: " + time2 + "ms");
- }
- // =============================================================================
- // 第十三部分:节流与防抖
- // =============================================================================
- // 节流函数
- function throttle(func, delay) {
- var lastCall = 0;
-
- return function() {
- var now = new Date().getTime();
-
- if (now - lastCall >= delay) {
- lastCall = now;
- return func.apply(this, arguments);
- }
- };
- }
- // 防抖函数
- function debounce(func, delay) {
- var timeoutId;
-
- return function() {
- var context = this;
- var args = arguments;
-
- clearTimeout(timeoutId);
- timeoutId = setTimeout(function() {
- func.apply(context, args);
- }, delay);
- };
- }
- // 演示节流
- function demoThrottling() {
- console.log("=== 节流示例 ===");
-
- var callCount = 0;
- var throttledFunction = throttle(function() {
- callCount++;
- console.log("函数被调用,总次数: " + callCount);
- }, 1000);
-
- for (var i = 0; i < 5; i++) {
- throttledFunction();
- var start = new Date().getTime();
- while (new Date().getTime() < start + 200) {}
- }
-
- console.log("最终调用次数: " + callCount);
- }
- // =============================================================================
- // 第十四部分:错误处理
- // =============================================================================
- // 安全除法函数
- function safeDivide(a, b) {
- try {
- if (typeof a !== 'number' || typeof b !== 'number') {
- throw new TypeError("参数必须是数字");
- }
-
- if (b === 0) {
- throw new Error("除数不能为零");
- }
-
- return a / b;
- } catch (error) {
- console.log("捕获到错误: " + error.name + " - " + error.message);
- return null;
- }
- }
- // 自定义错误类
- function CustomError(message, code) {
- this.name = "CustomError";
- this.message = message;
- this.code = code;
- this.timestamp = new Date().toISOString();
- }
- CustomError.prototype = Object.create(Error.prototype);
- CustomError.prototype.constructor = CustomError;
- // 演示错误处理
- function demoErrorHandling() {
- console.log("=== 错误处理示例 ===");
-
- console.log("10 ÷ 2 = " + safeDivide(10, 2));
- console.log("10 ÷ 0 = " + safeDivide(10, 0));
-
- try {
- throw new CustomError("自定义错误消息", "CUSTOM_CODE");
- } catch (error) {
- console.log("捕获自定义错误: " + error.message);
- }
- }
- // =============================================================================
- // 第十五部分:实战应用 - 用户管理
- // =============================================================================
- function User(id, name, email, age) {
- this.id = id;
- this.name = name;
- this.email = email;
- this.age = age;
-
- this.getInfo = function() {
- return {
- id: this.id,
- name: this.name,
- email: this.email,
- age: this.age
- };
- };
-
- this.isAdult = function() {
- return this.age >= 18;
- };
- }
- function UserManager() {
- this.users = [];
- this.nextId = 1;
-
- this.addUser = function(name, email, age) {
- var user = new User(this.nextId++, name, email, age);
- this.users.push(user);
- return user;
- };
-
- this.getAdultUsers = function() {
- var adults = [];
- for (var i = 0; i < this.users.length; i++) {
- if (this.users[i].isAdult()) {
- adults.push(this.users[i]);
- }
- }
- return adults;
- };
-
- this.getStats = function() {
- return {
- totalUsers: this.users.length,
- adultUsers: this.getAdultUsers().length
- };
- };
- }
- // 演示用户管理
- function demoUserManagement() {
- console.log("=== 用户管理示例 ===");
-
- var userManager = new UserManager();
-
- userManager.addUser("张三", "zhangsan@example.com", 25);
- userManager.addUser("李四", "lisi@example.com", 17);
- userManager.addUser("王五", "wangwu@example.com", 30);
-
- var stats = userManager.getStats();
- console.log("用户统计: " + JSON.stringify(stats));
- }
- // =============================================================================
- // 第十六部分:实战应用 - 数据处理器
- // =============================================================================
- function DataProcessor() {
- this.data = [];
-
- this.addData = function(item) {
- this.data.push(item);
- return this;
- };
-
- this.filter = function(predicate) {
- var filtered = [];
- for (var i = 0; i < this.data.length; i++) {
- if (predicate(this.data[i])) {
- filtered.push(this.data[i]);
- }
- }
- this.data = filtered;
- return this;
- };
-
- this.map = function(transformer) {
- var transformed = [];
- for (var i = 0; i < this.data.length; i++) {
- transformed.push(transformer(this.data[i]));
- }
- this.data = transformed;
- return this;
- };
-
- this.getResult = function() {
- return this.data;
- };
-
- this.reset = function() {
- this.data = [];
- return this;
- };
- }
- // 演示数据处理器
- function demoDataProcessor() {
- console.log("=== 数据处理器示例 ===");
-
- var processor = new DataProcessor();
-
- processor.addData(1).addData(2).addData(3).addData(4).addData(5).addData(6);
- console.log("原始数据: " + JSON.stringify(processor.getResult()));
-
- processor
- .filter(function(num) { return num % 2 === 0; })
- .map(function(num) { return num * 2; });
-
- console.log("偶数加倍后: " + JSON.stringify(processor.getResult()));
- }
- // =============================================================================
- // 主执行函数
- // =============================================================================
- function main() {
- console.log("===== JavaScript函数综合示例大全 =====");
- console.log("");
-
- // 基础部分
- demoBasicFunctions();
- delay(2000);
-
- demoReturnValues();
- delay(2000);
-
- demoClosures();
- delay(2000);
-
- demoHigherOrderFunctions();
- delay(2000);
-
- demoRecursion();
- delay(2000);
-
- demoConstructors();
- delay(2000);
-
- demoCallbacks();
- delay(2000);
-
- // 设计模式
- demoSingletonPattern();
- delay(2000);
-
- demoFactoryPattern();
- delay(2000);
-
- demoObserverPattern();
- delay(2000);
-
- // 异步编程
- demoPromise();
- delay(2000);
-
- // 性能优化
- demoMemoization();
- delay(2000);
-
- demoThrottling();
- delay(2000);
-
- // 错误处理
- demoErrorHandling();
- delay(2000);
-
- // 实战应用
- demoUserManagement();
- delay(2000);
-
- demoDataProcessor();
-
- console.log("");
- console.log("===== 所有示例执行完成 =====");
- }
- // 执行主函数
- main();
复制代码
| |  | |  |
|