YYPOST群发软件 发表于 2026-5-8 09:33:29

AIWROK软件示例数组方法实战应用

AIWROK软件示例数组方法实战应用




/**
* AIWROK数组方法实战应用示例
* 专为AIWROK安卓自动化环境设计的真实数组应用场景
*
* @功能特点
* - UI控件数组的查找、筛选和批量操作
* - 图像识别结果的数组处理和坐标计算
* - 设备信息数组的管理和查询
* - 任务队列数组的调度和执行
*
* @作者 AIWROK开发团队
* @版本 3.0 - 实战版
* @日期 2024
*/

//===========================================
// 基础兼容性设置
//===========================================

// AIWROK环境统一使用console.log输出日志

//===========================================
// 高级数组工具类 - 增强版
//===========================================

/**
* AdvancedArrayUtils - 高级数组操作工具类
* 提供链式调用、批量处理和性能优化功能
*/
function AdvancedArrayUtils() {
    this.version = "2.0.0";
    this.performanceMetrics = {
      operations: 0,
      startTime: 0,
      endTime: 0,
      memoryUsage: 0
    };
}

/**
* 开始性能监控
*/
AdvancedArrayUtils.prototype.startPerformanceMonitoring = function() {
    this.performanceMetrics.startTime = new Date().getTime();
    this.performanceMetrics.operations = 0;
    return this;
};

/**
* 结束性能监控并返回报告
*/
AdvancedArrayUtils.prototype.endPerformanceMonitoring = function() {
    this.performanceMetrics.endTime = new Date().getTime();
    var duration = this.performanceMetrics.endTime - this.performanceMetrics.startTime;
    return {
      duration: duration,
      operations: this.performanceMetrics.operations,
      opsPerSecond: Math.round(this.performanceMetrics.operations / (duration / 1000)),
      memoryUsage: this.performanceMetrics.memoryUsage
    };
};

/**
* 安全数组遍历 - 支持中断和异常处理
* @param {Array} array - 要遍历的数组
* @param {Function} callback - 回调函数,返回false可中断遍历
* @param {Object} context - 回调函数上下文
* @returns {AdvancedArrayUtils} 支持链式调用
*/
AdvancedArrayUtils.prototype.forEachSafe = function(array, callback, context) {
    if (!Array.isArray(array)) throw new Error('参数必须是数组');
    if (typeof callback !== 'function') throw new Error('回调函数必须是函数');
   
    context = context || this;
   
    try {
      for (var i = 0; i < array.length; i++) {
            this.performanceMetrics.operations++;
            var result = callback.call(context, array, i, array);
            if (result === false) break; // 支持主动中断
      }
    } catch (e) {
      console.log("数组遍历错误 at index " + i + ": " + (e.message || e));
    }
   
    return this;
};

/**
* 智能数组过滤 - 支持多条件和复杂逻辑
* @param {Array} array - 源数组
* @param {Array} conditions - 过滤条件数组
* @returns {Array} 过滤后的数组
*
* @示例
* var result = advancedArrayUtils.smartFilter(data, [
*   { field: 'age', operator: '>', value: 18 },
*   { field: 'name', operator: 'contains', value: '张' },
*   { field: 'score', operator: 'between', value: }
* ]);
*/
AdvancedArrayUtils.prototype.smartFilter = function(array, conditions) {
    if (!Array.isArray(array)) throw new Error('第一个参数必须是数组');
    if (!Array.isArray(conditions)) throw new Error('条件参数必须是数组');
   
    var self = this;
   
    return array.filter(function(item) {
      self.performanceMetrics.operations++;
      
      for (var i = 0; i < conditions.length; i++) {
            var condition = conditions;
            var fieldValue = self.getFieldValue(item, condition.field);
            
            if (!self.evaluateCondition(fieldValue, condition.operator, condition.value)) {
                return false;
            }
      }
      
      return true;
    });
};

/**
* 获取对象字段值 - 支持嵌套属性访问
*/
AdvancedArrayUtils.prototype.getFieldValue = function(obj, field) {
    if (!obj || !field) return undefined;
   
    var parts = field.split('.');
    var result = obj;
   
    for (var i = 0; i < parts.length; i++) {
      if (result === null || result === undefined) return undefined;
      result = result];
    }
   
    return result;
};

/**
* 评估条件 - 支持多种操作符
*/
AdvancedArrayUtils.prototype.evaluateCondition = function(fieldValue, operator, conditionValue) {
    switch (operator) {
      case '==': return fieldValue == conditionValue;
      case '===': return fieldValue === conditionValue;
      case '!=': return fieldValue != conditionValue;
      case '!==': return fieldValue !== conditionValue;
      case '>': return fieldValue > conditionValue;
      case '>=': return fieldValue >= conditionValue;
      case '<': return fieldValue < conditionValue;
      case '<=': return fieldValue <= conditionValue;
      case 'contains':
            return String(fieldValue).indexOf(conditionValue) !== -1;
      case 'startsWith':
            return String(fieldValue).indexOf(conditionValue) === 0;
      case 'endsWith':
            var str = String(fieldValue);
            return str.lastIndexOf(conditionValue) === str.length - conditionValue.length;
      case 'between':
            return fieldValue >= conditionValue && fieldValue <= conditionValue;
      case 'in':
            return conditionValue.indexOf(fieldValue) !== -1;
      case 'notIn':
            return conditionValue.indexOf(fieldValue) === -1;
      default:
            return false;
    }
};

/**
* 数组数据聚合 - 支持多种聚合函数
* @param {Array} array - 源数组
* @param {Object} config - 聚合配置
* @returns {Object} 聚合结果
*
* @示例
* var stats = advancedArrayUtils.aggregate(salesData, {
*   groupBy: 'category',
*   metrics: {
*         totalSales: { field: 'amount', operation: 'sum' },
*         avgPrice: { field: 'price', operation: 'avg' },
*         count: { operation: 'count' }
*   }
* });
*/
AdvancedArrayUtils.prototype.aggregate = function(array, config) {
    if (!Array.isArray(array)) throw new Error('参数必须是数组');
   
    var result = {};
    var self = this;
   
    // 分组处理
    if (config.groupBy) {
      var groups = {};
      
      array.forEach(function(item) {
            self.performanceMetrics.operations++;
            var groupKey = self.getFieldValue(item, config.groupBy);
            if (!groups) {
                groups = [];
            }
            groups.push(item);
      });
      
      // 对每个分组进行聚合
      for (var groupKey in groups) {
            if (groups.hasOwnProperty(groupKey)) {
                result = self.calculateMetrics(groups, config.metrics);
            }
      }
    } else {
      // 不分组,直接聚合
      result = this.calculateMetrics(array, config.metrics);
    }
   
    return result;
};

/**
* 计算指标 - 支持多种聚合操作
*/
AdvancedArrayUtils.prototype.calculateMetrics = function(array, metrics) {
    var result = {};
    var self = this;
   
    for (var metricName in metrics) {
      if (metrics.hasOwnProperty(metricName)) {
            var metric = metrics;
            result = self.calculateMetric(array, metric);
      }
    }
   
    return result;
};

/**
* 计算单个指标
*/
AdvancedArrayUtils.prototype.calculateMetric = function(array, metric) {
    var operation = metric.operation;
    var field = metric.field;
   
    switch (operation) {
      case 'count':
            return array.length;
            
      case 'sum':
            return array.reduce(function(sum, item) {
                return sum + (field ? this.getFieldValue(item, field) : item);
            }.bind(this), 0);
            
      case 'avg':
            var sum = array.reduce(function(sum, item) {
                return sum + (field ? this.getFieldValue(item, field) : item);
            }.bind(this), 0);
            return array.length > 0 ? sum / array.length : 0;
            
      case 'max':
            return Math.max.apply(Math, array.map(function(item) {
                return field ? this.getFieldValue(item, field) : item;
            }.bind(this)));
            
      case 'min':
            return Math.min.apply(Math, array.map(function(item) {
                return field ? this.getFieldValue(item, field) : item;
            }.bind(this)));
            
      default:
            return 0;
    }
};

/**
* 数组分页处理 - 支持大数据集的分页显示
* @param {Array} array - 源数组
* @param {number} pageSize - 每页大小
* @param {number} pageNumber - 页码(从1开始)
* @returns {Object} 分页结果
*/
AdvancedArrayUtils.prototype.paginate = function(array, pageSize, pageNumber) {
    if (!Array.isArray(array)) throw new Error('参数必须是数组');
   
    pageSize = Math.max(1, pageSize || 10);
    pageNumber = Math.max(1, pageNumber || 1);
   
    var totalItems = array.length;
    var totalPages = Math.ceil(totalItems / pageSize);
    var startIndex = (pageNumber - 1) * pageSize;
    var endIndex = Math.min(startIndex + pageSize, totalItems);
   
    return {
      items: array.slice(startIndex, endIndex),
      pagination: {
            pageNumber: pageNumber,
            pageSize: pageSize,
            totalItems: totalItems,
            totalPages: totalPages,
            hasPrevious: pageNumber > 1,
            hasNext: pageNumber < totalPages,
            startIndex: startIndex,
            endIndex: endIndex - 1
      }
    };
};

/**
* 数组去重 - 支持复杂对象的去重
* @param {Array} array - 源数组
* @param {string|Function} keySelector - 用于去重的键选择器
* @returns {Array} 去重后的数组
*/
AdvancedArrayUtils.prototype.distinct = function(array, keySelector) {
    if (!Array.isArray(array)) throw new Error('参数必须是数组');
   
    var seen = {};
    var result = [];
    var self = this;
   
    array.forEach(function(item) {
      self.performanceMetrics.operations++;
      
      var key;
      if (typeof keySelector === 'function') {
            key = keySelector(item);
      } else if (typeof keySelector === 'string') {
            key = self.getFieldValue(item, keySelector);
      } else {
            key = item;
      }
      
      var keyString = String(key);
      if (!seen.hasOwnProperty(keyString)) {
            seen = true;
            result.push(item);
      }
    });
   
    return result;
};

//===========================================
// AIWROK特定功能集成
//===========================================

/**
* UI控件批量处理 - 结合AIWROK的UI操作
* @param {Array} uiElements - UI元素数组
* @param {Function} processor - 处理函数
* @param {Object} options - 处理选项
*/
AdvancedArrayUtils.prototype.batchUIProcess = function(uiElements, processor, options) {
    options = options || {};
    var batchSize = options.batchSize || 10;
    var delay = options.delay || 100;
    var self = this;
   
    console.log("开始批量处理 " + uiElements.length + " 个UI元素");
   
    var batches = [];
    for (var i = 0; i < uiElements.length; i += batchSize) {
      batches.push(uiElements.slice(i, i + batchSize));
    }
   
    // 分批处理(AIWROK环境使用threads.sleep代替setTimeout)
    for (var batchIndex = 0; batchIndex < batches.length; batchIndex++) {
      var batch = batches;
      console.log("处理第 " + (batchIndex + 1) + " 批,共 " + batch.length + " 个元素");
      
      batch.forEach(function(element, index) {
            try {
                processor(element, index);
                self.performanceMetrics.operations++;
            } catch (e) {
                console.log("处理UI元素失败: " + (e.message || e));
            }
      });
      
      // 批次间延时
      if (batchIndex < batches.length - 1) {
            sleep.second(delay / 1000);
      }
    }
   
    console.log("批量处理完成");
   
    return this;
};

/**
* OCR结果智能筛选 - 结合AIWROK的OCR功能
* @param {Array} ocrResults - OCR识别结果数组
* @param {Object} filterOptions - 筛选选项
* @returns {Array} 筛选后的结果
*/
AdvancedArrayUtils.prototype.filterOCRResults = function(ocrResults, filterOptions) {
    filterOptions = filterOptions || {};
   
    var conditions = [];
   
    // 文本长度过滤
    if (filterOptions.minLength) {
      conditions.push({
            field: 'text',
            operator: '>',
            value: filterOptions.minLength
      });
    }
   
    // 置信度过滤
    if (filterOptions.minConfidence) {
      conditions.push({
            field: 'confidence',
            operator: '>=',
            value: filterOptions.minConfidence
      });
    }
   
    // 文本内容过滤
    if (filterOptions.contains) {
      conditions.push({
            field: 'text',
            operator: 'contains',
            value: filterOptions.contains
      });
    }
   
    // 位置过滤
    if (filterOptions.minX !== undefined) {
      conditions.push({
            field: 'x',
            operator: '>=',
            value: filterOptions.minX
      });
    }
   
    return this.smartFilter(ocrResults, conditions);
};

/**
* 日志数据聚合分析 - 结合AIWROK的日志功能
* @param {Array} logEntries - 日志条目数组
* @param {Object} analysisConfig - 分析配置
* @returns {Object} 分析结果
*/
AdvancedArrayUtils.prototype.analyzeLogs = function(logEntries, analysisConfig) {
    analysisConfig = analysisConfig || {};
   
    var timeWindow = analysisConfig.timeWindow || 3600000; // 1小时
    var logLevelWeights = analysisConfig.logLevelWeights || {
      'ERROR': 10,
      'WARN': 5,
      'INFO': 1,
      'DEBUG': 0.5
    };
   
    var currentTime = new Date().getTime();
    var recentLogs = logEntries.filter(function(log) {
      return currentTime - log.timestamp <= timeWindow;
    });
   
    var analysis = {
      totalLogs: recentLogs.length,
      levelDistribution: {},
      errorRate: 0,
      warningRate: 0,
      healthScore: 100
    };
   
    // 统计日志级别分布
    recentLogs.forEach(function(log) {
      var level = log.level || 'INFO';
      analysis.levelDistribution = (analysis.levelDistribution || 0) + 1;
    });
   
    // 计算错误率和警告率
    var errorCount = analysis.levelDistribution['ERROR'] || 0;
    var warnCount = analysis.levelDistribution['WARN'] || 0;
   
    analysis.errorRate = analysis.totalLogs > 0 ? (errorCount / analysis.totalLogs) * 100 : 0;
    analysis.warningRate = analysis.totalLogs > 0 ? (warnCount / analysis.totalLogs) * 100 : 0;
   
    // 计算健康分数
    var totalWeight = 0;
    var weightedScore = 0;
   
    for (var level in analysis.levelDistribution) {
      if (analysis.levelDistribution.hasOwnProperty(level)) {
            var count = analysis.levelDistribution;
            var weight = logLevelWeights || 1;
            totalWeight += count * weight;
            weightedScore += count * weight;
      }
    }
   
    if (totalWeight > 0) {
      analysis.healthScore = Math.max(0, 100 - (errorCount * 10) - (warnCount * 3));
    }
   
    return analysis;
};

//===========================================
// 使用示例和测试
//===========================================

function uiControlArrayExample() {
    console.log("=== 示例1: UI控件数组操作 ===");
   
    // 模拟通过findControls获取的UI控件数组
    var uiControls = [
      { id: 'btn_login', type: 'Button', text: '登录', visible: true, enabled: true, x: 100, y: 200, width: 200, height: 80 },
      { id: 'btn_register', type: 'Button', text: '注册', visible: true, enabled: true, x: 100, y: 300, width: 200, height: 80 },
      { id: 'input_username', type: 'EditText', text: '', visible: true, enabled: true, x: 50, y: 100, width: 300, height: 60 },
      { id: 'input_password', type: 'EditText', text: '', visible: true, enabled: true, x: 50, y: 170, width: 300, height: 60 },
      { id: 'chk_remember', type: 'CheckBox', text: '记住密码', visible: true, enabled: true, x: 50, y: 250, width: 150, height: 40 },
      { id: 'txt_forgot', type: 'TextView', text: '忘记密码?', visible: true, enabled: true, x: 250, y: 250, width: 120, height: 40 },
      { id: 'btn_cancel', type: 'Button', text: '取消', visible: false, enabled: false, x: 100, y: 400, width: 200, height: 80 }
    ];
   
    console.log("找到 " + uiControls.length + " 个UI控件");
   
    // 1. 筛选所有可见且可用的按钮
    var clickableButtons = [];
    for (var i = 0; i < uiControls.length; i++) {
      var ctrl = uiControls;
      if (ctrl.type === 'Button' && ctrl.visible && ctrl.enabled) {
            clickableButtons.push(ctrl);
      }
    }
   
    console.log("可点击的按钮有 " + clickableButtons.length + " 个:");
    for (var j = 0; j < clickableButtons.length; j++) {
      console.log("- " + clickableButtons.text + " (位置: " + clickableButtons.x + "," + clickableButtons.y + ")");
    }
   
    // 2. 查找特定文本的控件
    var loginButton = null;
    for (var k = 0; k < uiControls.length; k++) {
      if (uiControls.text === '登录') {
            loginButton = uiControls;
            break;
      }
    }
   
    if (loginButton) {
      console.log("找到登录按钮:");
      console.log("ID: " + loginButton.id);
      console.log("类型: " + loginButton.type);
      console.log("位置: (" + loginButton.x + ", " + loginButton.y + ")");
      console.log("尺寸: " + loginButton.width + "x" + loginButton.height);
      console.log("中心点: (" + (loginButton.x + loginButton.width/2) + ", " + (loginButton.y + loginButton.height/2) + ")");
    }
   
    // 3. 批量计算控件中心坐标(用于点击操作)
    console.log("所有输入框的中心坐标:");
    for (var m = 0; m < uiControls.length; m++) {
      var control = uiControls;
      if (control.type === 'EditText') {
            var centerX = control.x + control.width / 2;
            var centerY = control.y + control.height / 2;
            console.log("" + control.id + ": (" + centerX + ", " + centerY + ")");
      }
    }
   
    // 步骤间延时2秒
    console.log("等待2秒...");
    sleep.second(2);
}

/**
* 图像识别结果数组处理示例
*/
function imageRecognitionArrayExample() {
    console.log("=== 示例2: 图像识别结果数组处理 ===");
   
    // 模拟通过findImage或shapeSearch返回的识别结果数组
    var recognitionResults = [
      { name: '登录按钮', confidence: 0.95, x: 150, y: 300, width: 180, height: 60, timestamp: new Date().getTime() },
      { name: '登录按钮', confidence: 0.92, x: 152, y: 298, width: 178, height: 62, timestamp: new Date().getTime() + 100 },
      { name: '提交按钮', confidence: 0.88, x: 200, y: 500, width: 160, height: 55, timestamp: new Date().getTime() + 200 },
      { name: '验证码图片', confidence: 0.75, x: 100, y: 400, width: 200, height: 80, timestamp: new Date().getTime() + 300 },
      { name: '登录按钮', confidence: 0.90, x: 148, y: 302, width: 182, height: 58, timestamp: new Date().getTime() + 400 }
    ];
   
    console.log("识别到 " + recognitionResults.length + " 个目标");
   
    // 1. 筛选高置信度的结果(>0.85)
    var highConfidenceResults = [];
    for (var i = 0; i < recognitionResults.length; i++) {
      if (recognitionResults.confidence > 0.85) {
            highConfidenceResults.push(recognitionResults);
      }
    }
   
    console.log("高置信度结果(>0.85)有 " + highConfidenceResults.length + " 个:");
    for (var j = 0; j < highConfidenceResults.length; j++) {
      var result = highConfidenceResults;
      console.log("- " + result.name + " (置信度: " + result.confidence + ", 位置: " + result.x + "," + result.y + ")");
    }
   
    // 2. 按名称分组统计
    var groupedByName = {};
    for (var k = 0; k < recognitionResults.length; k++) {
      var item = recognitionResults;
      if (!groupedByName) {
            groupedByName = [];
      }
      groupedByName.push(item);
    }
   
    console.log("按名称分组统计:");
    for (var name in groupedByName) {
      if (groupedByName.hasOwnProperty(name)) {
            var items = groupedByName;
            console.log("" + name + ": " + items.length + " 次匹配");
            
            // 计算平均置信度
            var totalConfidence = 0;
            for (var m = 0; m < items.length; m++) {
                totalConfidence += items.confidence;
            }
            var avgConfidence = totalConfidence / items.length;
            console.log("    平均置信度: " + avgConfidence.toFixed(3));
            
            // 找到最佳匹配(最高置信度)
            var bestMatch = items;
            for (var n = 1; n < items.length; n++) {
                if (items.confidence > bestMatch.confidence) {
                  bestMatch = items;
                }
            }
            console.log("    最佳匹配: (" + bestMatch.x + ", " + bestMatch.y + ") 置信度: " + bestMatch.confidence);
      }
    }
   
    // 3. 计算多个匹配点的中心位置(用于提高点击精度)
    var loginButtons = groupedByName['登录按钮'];
    if (loginButtons && loginButtons.length > 0) {
      var sumX = 0, sumY = 0;
      for (var p = 0; p < loginButtons.length; p++) {
            sumX += loginButtons.x + loginButtons.width / 2;
            sumY += loginButtons.y + loginButtons.height / 2;
      }
      var centerX = sumX / loginButtons.length;
      var centerY = sumY / loginButtons.length;
      
      console.log("登录按钮的平均中心位置:");
      console.log("X: " + Math.round(centerX));
      console.log("Y: " + Math.round(centerY));
      console.log("建议点击坐标: (" + Math.round(centerX) + ", " + Math.round(centerY) + ")");
    }
   
    // 步骤间延时2秒
    console.log("等待2秒...");
    sleep.second(2);
}

/**
* 任务队列数组调度示例
*/
function taskQueueArrayExample() {
    console.log("=== 示例3: 任务队列数组调度 ===");
   
    // 模拟任务队列数组
    var taskQueue = [
      { id: 1, name: '打开应用', priority: 1, status: 'pending', duration: 2000 },
      { id: 2, name: '等待首页加载', priority: 2, status: 'pending', duration: 3000 },
      { id: 3, name: '点击登录按钮', priority: 3, status: 'pending', duration: 1000 },
      { id: 4, name: '输入用户名', priority: 4, status: 'pending', duration: 1500 },
      { id: 5, name: '输入密码', priority: 5, status: 'pending', duration: 1500 },
      { id: 6, name: '点击提交', priority: 6, status: 'pending', duration: 1000 },
      { id: 7, name: '验证登录结果', priority: 7, status: 'pending', duration: 2000 }
    ];
   
    console.log("任务队列共有 " + taskQueue.length + " 个任务");
   
    // 1. 按优先级排序
    taskQueue.sort(function(a, b) {
      return a.priority - b.priority;
    });
   
    console.log("按优先级排序后的任务列表:");
    for (var i = 0; i < taskQueue.length; i++) {
      var task = taskQueue;
      console.log("[" + task.priority + "] " + task.name + " (预计耗时: " + task.duration + "ms)");
    }
   
    // 2. 模拟执行任务队列
    console.log("开始执行任务队列:");
    var completedTasks = [];
    var failedTasks = [];
   
    for (var j = 0; j < taskQueue.length; j++) {
      var currentTask = taskQueue;
      console.log("执行任务 #" + (j+1) + ": " + currentTask.name);
      
      // 模拟任务执行(成功率90%)
      var success = Math.random() > 0.1;
      
      if (success) {
            currentTask.status = 'completed';
            completedTasks.push(currentTask);
            console.log("    ✓ 完成");
      } else {
            currentTask.status = 'failed';
            failedTasks.push(currentTask);
            console.log("    ✗ 失败");
      }
      
      // 任务间短暂延时
      sleep.second(0.3);
    }
   
    console.log("");
    console.log("任务执行统计:");
    console.log("总任务数: " + taskQueue.length);
    console.log("成功: " + completedTasks.length);
    console.log("失败: " + failedTasks.length);
    console.log("成功率: " + (completedTasks.length / taskQueue.length * 100).toFixed(1) + "%");
   
    if (failedTasks.length > 0) {
      console.log("");
      console.log("失败的任务:");
      for (var k = 0; k < failedTasks.length; k++) {
            console.log("- " + failedTasks.name);
      }
    }
   
    // 步骤间延时2秒
    console.log("等待2秒...");
    sleep.second(2);
}

/**
* 设备信息数组管理示例
*/
function deviceInfoArrayExample() {
    console.log("=== 示例4: 设备信息数组管理 ===");
   
    // 模拟多设备信息数组
    var devices = [
      { deviceId: 'device_001', model: '小米11', androidVersion: '12', screenWidth: 1080, screenHeight: 2400, battery: 85, online: true },
      { deviceId: 'device_002', model: '华为P40', androidVersion: '11', screenWidth: 1080, screenHeight: 2340, battery: 62, online: true },
      { deviceId: 'device_003', model: 'OPPO Reno6', androidVersion: '11', screenWidth: 1080, screenHeight: 2400, battery: 45, online: false },
      { deviceId: 'device_004', model: 'vivo X60', androidVersion: '12', screenWidth: 1080, screenHeight: 2376, battery: 90, online: true },
      { deviceId: 'device_005', model: '三星S21', androidVersion: '13', screenWidth: 1080, screenHeight: 2400, battery: 30, online: true }
    ];
   
    console.log("设备列表共有 " + devices.length + " 台设备");
   
    // 1. 筛选在线设备
    var onlineDevices = [];
    for (var i = 0; i < devices.length; i++) {
      if (devices.online) {
            onlineDevices.push(devices);
      }
    }
   
    console.log("在线设备: " + onlineDevices.length + " 台");
    for (var j = 0; j < onlineDevices.length; j++) {
      var device = onlineDevices;
      console.log("- " + device.model + " (电量: " + device.battery + "%, Android " + device.androidVersion + ")");
    }
   
    // 2. 查找低电量设备(<50%)
    var lowBatteryDevices = [];
    for (var k = 0; k < devices.length; k++) {
      if (devices.battery < 50) {
            lowBatteryDevices.push(devices);
      }
    }
   
    if (lowBatteryDevices.length > 0) {
      console.log("低电量设备警告 (<50%): " + lowBatteryDevices.length + " 台");
      for (var m = 0; m < lowBatteryDevices.length; m++) {
            var lowDevice = lowBatteryDevices;
            console.log("⚠ " + lowDevice.model + " - 电量: " + lowDevice.battery + "%");
      }
    } else {
      console.log("所有设备电量充足");
    }
   
    // 3. 按Android版本分组
    var versionGroups = {};
    for (var n = 0; n < devices.length; n++) {
      var dev = devices;
      var version = 'Android ' + dev.androidVersion;
      if (!versionGroups) {
            versionGroups = [];
      }
      versionGroups.push(dev);
    }
   
    console.log("按Android版本分组:");
    for (var version in versionGroups) {
      if (versionGroups.hasOwnProperty(version)) {
            var group = versionGroups;
            console.log("" + version + ": " + group.length + " 台设备");
            for (var p = 0; p < group.length; p++) {
                console.log("    - " + group.model);
            }
      }
    }
   
    // 4. 计算平均电量
    var totalBattery = 0;
    for (var q = 0; q < devices.length; q++) {
      totalBattery += devices.battery;
    }
    var avgBattery = totalBattery / devices.length;
   
    console.log("设备统计信息:");
    console.log("平均电量: " + avgBattery.toFixed(1) + "%");
    console.log("最高电量: " + Math.max.apply(Math, devices.map(function(d) { return d.battery; })) + "%");
    console.log("最低电量: " + Math.min.apply(Math, devices.map(function(d) { return d.battery; })) + "%");
   
    // 步骤间延时2秒
    console.log("等待2秒...");
    sleep.second(2);
}

//===========================================
// 主函数和执行入口
//===========================================

/**
* 运行所有示例
*/
function runAllExamples() {
    try {
      uiControlArrayExample();
      imageRecognitionArrayExample();
      taskQueueArrayExample();
      deviceInfoArrayExample();
      console.log("=== 所有示例执行完成 ===");
    } catch (e) {
      console.log("执行示例时发生错误: " + (e.message || e));
    }
}

// 执行所有示例
runAllExamples();

页: [1]
查看完整版本: AIWROK软件示例数组方法实战应用