YYPOST群发软件 发表于 2025-12-25 08:10:19

AIWROK软件对象工具函数库例子

AIWROK软件对象工具函数库例子






/**
* //🍎交流QQ群711841924群一,苹果内测群,528816639
* 通用对象操作工具函数库
* 适用本文档ES5系统安卓 JavaScript引擎Rhino
* 提供实用的对象操作方法,解决实际项目中的常见问题
*/

print.log("开始执行日志窗口操作");
print.log("1. 显示日志窗口");
printl( logWindow.show())
print.log("日志窗口显示完成");

print.log("2. 清空日志窗口");
printl(logWindow.clear())
print.log("日志窗口清空完成");

print.log("3. 设置日志窗口高度为2500");
printl(logWindow.setHeight(2500))
print.log("日志窗口高度设置完成");

print.log("4. 设置日志窗口宽度为1000");
printl(logWindow.setWidth(1000))
print.log("日志窗口宽度设置完成");

print.log("5. 设置日志窗口为不可点击模式");
printl(logWindow.setNoClickModel())
print.log("日志窗口不可点击模式设置完成");
print.log("所有日志窗口操作执行完毕");

// 合并对象 - 将多个对象合并为一个新对象
function mergeObjects() {
    print.log("执行mergeObjects函数 - 合并多个对象");
    var target = {};
    var i, source;
   
    for (i = 0; i < arguments.length; i++) {
      source = arguments;
      print.log("- 合并第" + (i + 1) + "个对象: " + safeStringify(source));
      if (source != null && typeof source === 'object') {
            for (var key in source) {
                if (source.hasOwnProperty(key)) {
                  target = source;
                }
            }
      }
    }
   
    print.log("- 合并结果: " + safeStringify(target));
    print.log("- 结果: 拷贝成功,目标对象变为: " + safeStringify(target));
    return target;
}

// 获取对象键值对 - 返回[, , ...]格式数组
function getObjectEntries(obj) {
    print.log("执行getObjectEntries函数 - 获取对象键值对");
    print.log("- 对象: " + safeStringify(obj));
    var entries = [];
    var key;
   
    if (obj != null && typeof obj === 'object') {
      for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                entries.push(]);
            }
      }
    }
   
    print.log("- 结果: " + safeStringify(entries));
    return entries;
}

// 获取对象键数组
function getObjectKeys(obj) {
    print.log("执行getObjectKeys函数 - 获取对象键数组");
    print.log("- 对象: " + safeStringify(obj));
    var keys = [];
    var key;
   
    if (obj != null && typeof obj === 'object') {
      for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                keys.push(key);
            }
      }
    }
   
    print.log("- 结果: " + safeStringify(keys));
    return keys;
}

// 获取对象值数组
function getObjectValues(obj) {
    print.log("执行getObjectValues函数 - 获取对象值数组");
    print.log("- 对象: " + safeStringify(obj));
    var values = [];
    var key;
   
    if (obj != null && typeof obj === 'object') {
      for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                values.push(obj);
            }
      }
    }
   
    print.log("- 结果: " + safeStringify(values));
    return values;
}

// 冻结对象 - 防止对象被修改
function freezeObject(obj) {
    print.log("执行freezeObject函数 - 冻结对象");
    print.log("- 对象: " + safeStringify(obj));
    if (obj != null && typeof obj === 'object') {
      var frozen = Object.freeze(obj);
      print.log("- 结果: 对象已冻结");
      return frozen;
    }
    print.log("- 结果: 对象为null或非对象类型,直接返回");
    print.log("- 结果: " + safeStringify(obj));
    return obj;
}

// 检查对象是否被冻结
function isObjectFrozen(obj) {
    print.log("执行isObjectFrozen函数 - 检查对象是否被冻结");
    print.log("- 对象: " + safeStringify(obj));
    var result;
    if (obj != null && typeof obj === 'object') {
      result = Object.isFrozen(obj);
    } else {
      result = false;
    }
    print.log("- 结果: " + (result ? "对象已被冻结" : "对象未被冻结"));
    print.log("- 结果: " + safeStringify(result));
    print.log("- 结果: " + safeStringify(result));
    print.log("- 结果: 转换成功");
    print.log("- 结果: 扁平化成功,扁平对象: " + safeStringify(result));
    return result;
}

// 深度克隆对象 - 支持嵌套对象和数组
function deepCloneObject(obj) {
    print.log("执行deepCloneObject函数 - 深度克隆对象");
    print.log("- 对象: " + safeStringify(obj));
    var clone;
    var i, key;
   
    if (obj == null || typeof obj !== 'object') {
      print.log("- 结果: 对象为null或非对象类型,直接返回");
      return obj;
    }
   
    // 处理数组
    if (obj instanceof Array) {
      clone = [];
      for (i = 0; i < obj.length; i++) {
            clone = deepCloneObject(obj);
      }
    }
    // 处理对象
    else {
      clone = {};
      for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                clone = deepCloneObject(obj);
            }
      }
    }
   
    print.log("- 结果: 克隆成功");
    return clone;
}

// 1. 对象属性安全获取 - 避免undefined错误
function getSafe(obj, path, defaultValue) {
    print.log("执行getSafe函数 - 安全获取对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 路径: " + path);
   
    if (obj == null) {
      print.log("- 结果: 对象为null,返回默认值: " + defaultValue);
      return defaultValue;
    }
   
    var keys = path.split('.');
    var current = obj;
   
    for (var i = 0; i < keys.length; i++) {
      if (current == null || !current.hasOwnProperty(keys)) {
            print.log("- 结果: 路径不存在,返回默认值: " + defaultValue);
            return defaultValue;
      }
      current = current];
    }
   
    print.log("- 结果: 获取成功,值为: " + safeStringify(current));
    return current;
}

// 2. 对象比较 - 深度比较两个对象是否相等
function isEqual(obj1, obj2) {
    print.log("执行isEqual函数 - 深度比较两个对象是否相等");
    print.log("- 对象1: " + safeStringify(obj1));
    print.log("- 对象2: " + safeStringify(obj2));
    if (obj1 === obj2) {
      print.log("- 结果: 对象引用相同,直接返回true");
      print.log("- 结果: 对象深度比较,相等");
    return true;
    }
   
    if (obj1 == null || obj2 == null) {
      print.log("- 结果: 其中一个对象为null,返回false");
      return false;
    }
   
    if (typeof obj1 !== typeof obj2) {
      print.log("- 结果: 对象类型不同,返回false");
      return false;
    }
   
    if (typeof obj1 !== 'object') {
      var result = obj1 === obj2;
      print.log("- 结果: 基础类型比较," + (result ? "相等" : "不相等"));
      return result;
    }
   
    if (obj1 instanceof Array && obj2 instanceof Array) {
      if (obj1.length !== obj2.length) return false;
      for (var i = 0; i < obj1.length; i++) {
            if (!isEqual(obj1, obj2)) return false;
      }
      return true;
    }
   
    if (obj1 instanceof Array || obj2 instanceof Array) return false;
   
    var keys1 = getObjectKeys(obj1);
    var keys2 = getObjectKeys(obj2);
   
    if (keys1.length !== keys2.length) return false;
   
    for (var j = 0; j < keys1.length; j++) {
      var key = keys1;
      if (!obj2.hasOwnProperty(key) || !isEqual(obj1, obj2)) {
            return false;
      }
    }
   
    return true;
}

// 3. 对象过滤 - 保留符合条件的属性
function filterObject(obj, predicate) {
    print.log("执行filterObject函数 - 过滤对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 过滤条件: " + predicate.toString());
    if (obj == null || typeof obj !== 'object' || typeof predicate !== 'function') {
      print.log("- 结果: 参数无效,返回空对象");
      return {};
    }
   
    var result = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key) && predicate(obj, key, obj)) {
            result = obj;
      }
    }
    return result;
}

// 4. 对象转换为Map - 适合需要键值对操作的场景
function objectToMap(obj) {
    print.log("执行objectToMap函数 - 对象转换为Map");
    print.log("- 对象: " + safeStringify(obj));
    if (obj == null || typeof obj !== 'object') {
      print.log("- 结果: 对象为null或非对象类型,返回空Map");
      return new HashMap();
    }
   
    var map = new HashMap();
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            map.put(key, obj);
      }
    }
    print.log("- 结果: 转换成功,Map大小: " + map.size());
    return map;
}

// 5. Map转换为对象
function mapToObject(map) {
    print.log("执行mapToObject函数 - Map转换为对象");
    print.log("- Map: " + map.toString());
    if (map == null || typeof map !== 'object' || typeof map.entrySet !== 'function') {
      print.log("- 结果: Map无效,返回空对象");
      return {};
    }
   
    var obj = {};
    var entries = map.entrySet().toArray();
    for (var i = 0; i < entries.length; i++) {
      var entry = entries;
      obj = entry.getValue();
    }
    return obj;
}

// 6. 对象属性遍历 - 对每个属性执行回调函数
function forEachObject(obj, callback) {
    print.log("执行forEachObject函数 - 遍历对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 回调函数: " + callback.toString());
    if (obj == null || typeof obj !== 'object' || typeof callback !== 'function') {
      print.log("- 结果: 参数无效,直接返回");
      return;
    }
   
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            print.log("- 处理属性: " + key + " = " + safeStringify(obj));
            callback(obj, key, obj);
      }
    }
    print.log("- 结果: 遍历完成");
}

// 7. 对象属性转换 - 转换对象的属性值
function transformObject(obj, transformer) {
    print.log("执行transformObject函数 - 转换对象属性值");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 转换函数: " + transformer.toString());
    if (obj == null || typeof obj !== 'object' || typeof transformer !== 'function') {
      print.log("- 结果: 参数无效,返回空对象");
      return {};
    }
   
    var result = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            result = transformer(obj, key, obj);
      }
    }
    return result;
}

// 8. 检查对象是否包含指定属性
function hasOwnProperty(obj, key) {
    print.log("执行hasOwnProperty函数 - 检查对象属性是否存在");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 属性: " + key);
    var result;
    if (obj == null || typeof obj !== 'object') {
      result = false;
    } else {
      result = obj.hasOwnProperty(key);
    }
    print.log("- 结果: " + (result ? "存在" : "不存在"));
    return result;
}

// 9. 获取对象大小(属性数量)
function getObjectSize(obj) {
    print.log("执行getObjectSize函数 - 获取对象属性数量");
    print.log("- 对象: " + safeStringify(obj));
    var count = 0;
    if (obj == null || typeof obj !== 'object') {
      count = 0;
    } else {
      for (var key in obj) {
            if (obj.hasOwnProperty(key)) count++;
      }
    }
    print.log("- 结果: 属性数量为" + count);
    return count;
}

// 10. 对象序列化增强 - 处理循环引用和特殊类型
function safeStringify(obj, space) {
    print.log("执行safeStringify函数 - 对象序列化");
    try {
      var cache = [];
      var result = JSON.stringify(obj, function(key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                  return '';
                }
                cache.push(value);
            }
            return value;
      }, space);
      cache = null; // 释放内存
      return result;
    } catch (e) {
      print.log("- 结果: 序列化失败,返回空对象字符串");
      return '{}';
    }
}

// 11. 对象属性更新 - 安全更新对象属性,支持嵌套路径
function updateObject(obj, path, value) {
    print.log("执行updateObject函数 - 更新对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 路径: " + path);
    print.log("- 新值: " + safeStringify(value));
    if (obj == null || typeof obj !== 'object') {
      print.log("- 结果: 对象为null或非对象类型,直接返回");
      return obj;
    }
   
    var keys = path.split('.');
    var current = obj;
   
    for (var i = 0; i < keys.length - 1; i++) {
      var key = keys;
      if (!current || typeof current !== 'object') {
            current = {};
      }
      current = current;
    }
   
    current] = value;
    print.log("- 结果: 更新成功,对象变为: " + safeStringify(obj));
    return obj;
}

// 12. 对象属性删除 - 安全删除对象属性,支持嵌套路径
function deleteProperty(obj, path) {
    print.log("执行deleteProperty函数 - 删除对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 路径: " + path);
    if (obj == null || typeof obj !== 'object') {
      print.log("- 结果: 对象为null或非对象类型,直接返回");
      return obj;
    }
   
    var keys = path.split('.');
    var current = obj;
   
    for (var i = 0; i < keys.length - 1; i++) {
      var key = keys;
      if (!current || typeof current !== 'object') {
            print.log("- 结果: 路径不存在,直接返回原对象");
            return obj;
      }
      current = current;
    }
   
    delete current];
    print.log("- 结果: 删除成功,对象变为: " + safeStringify(obj));
    return obj;
}

// 13. 对象属性遍历并转换 - 深度转换对象的所有属性
function deepTransform(obj, transformer) {
    print.log("执行deepTransform函数 - 深度转换对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 转换函数: " + transformer.toString());
    if (obj == null || typeof obj !== 'object' || typeof transformer !== 'function') {
      print.log("- 结果: 参数无效,直接返回");
      return obj;
    }
   
    if (obj instanceof Array) {
      return obj.map(function(item) {
            return deepTransform(item, transformer);
      });
    }
   
    var result = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            var value = obj;
            if (typeof value === 'object' && value !== null) {
                result = deepTransform(value, transformer);
            } else {
                result = transformer(value, key, obj);
            }
      }
    }
    return result;
}

// 14. 对象扁平化 - 将嵌套对象转换为扁平结构
function flattenObject(obj, prefix) {
    print.log("执行flattenObject函数 - 扁平化嵌套对象");
    print.log("- 嵌套对象: " + safeStringify(obj));
    if (obj == null || typeof obj !== 'object') {
      print.log("- 结果: 参数无效,直接返回");
      return obj;
    }
   
    var result = {};
    prefix = prefix || '';
   
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            var fullPath = prefix ? prefix + '.' + key : key;
            var value = obj;
            
            if (typeof value === 'object' && value !== null && !(value instanceof Array)) {
                var flatChild = flattenObject(value, fullPath);
                for (var childKey in flatChild) {
                  if (flatChild.hasOwnProperty(childKey)) {
                        result = flatChild;
                  }
                }
            } else {
                result = value;
            }
      }
    }
    return result;
}

// 15. 扁平对象还原 - 将扁平结构转换为嵌套对象
function unflattenObject(flatObj) {
    print.log("执行unflattenObject函数 - 还原扁平对象");
    print.log("- 扁平对象: " + safeStringify(flatObj));
    if (flatObj == null || typeof flatObj !== 'object') {
      print.log("- 结果: 参数无效,直接返回");
      return flatObj;
    }
   
    var result = {};
   
    for (var key in flatObj) {
      if (flatObj.hasOwnProperty(key)) {
            print.log("- 还原属性: " + key + " = " + safeStringify(flatObj));
            updateObject(result, key, flatObj);
      }
    }
    print.log("- 结果: 还原成功,嵌套对象: " + safeStringify(result));
    return result;
}

// 16. 对象属性存在性检查 - 检查嵌套属性是否存在
function hasNestedProperty(obj, path) {
    print.log("执行hasNestedProperty函数 - 检查嵌套属性是否存在");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 路径: " + path);
    if (obj == null || typeof obj !== 'object') {
      print.log("- 结果: 对象为null或非对象类型,返回false");
      return false;
    }
   
    var keys = path.split('.');
    var current = obj;
   
    for (var i = 0; i < keys.length; i++) {
      var key = keys;
      if (!current.hasOwnProperty(key)) {
            print.log("- 结果: 路径" + keys.slice(0, i + 1).join('.') + "不存在,返回false");
            return false;
      }
      current = current;
    }
    print.log("- 结果: 路径存在");
    return true;
}

// 17. 对象属性拷贝 - 从一个对象拷贝属性到另一个对象
function copyProperties(source, target, properties) {
    print.log("执行copyProperties函数 - 拷贝对象属性");
    print.log("- 源对象: " + safeStringify(source));
    print.log("- 目标对象: " + safeStringify(target));
    print.log("- 指定属性: " + safeStringify(properties));
    if (source == null || typeof source !== 'object' || target == null || typeof target !== 'object') {
      print.log("- 结果: 参数无效,返回目标对象");
      return target;
    }
   
    if (!properties || !(properties instanceof Array)) {
      // 拷贝所有属性
      for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target = source;
            }
      }
    } else {
      // 只拷贝指定属性
      for (var i = 0; i < properties.length; i++) {
            var key = properties;
            if (source.hasOwnProperty(key)) {
                target = source;
            }
      }
    }
    return target;
}

// 18. 对象属性重命名 - 重命名对象的属性
function renameProperties(obj, mapping) {
    print.log("执行renameProperties函数 - 重命名对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 映射关系: " + safeStringify(mapping));
    if (obj == null || typeof obj !== 'object' || mapping == null || typeof mapping !== 'object') {
      print.log("- 结果: 参数无效,直接返回");
      return obj;
    }
   
    var result = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            var newKey = mapping || key;
            print.log("- 重命名: " + key + " -> " + newKey + " = " + safeStringify(obj));
            result = obj;
      }
    }
    print.log("- 结果: 重命名成功,对象变为: " + safeStringify(result));
    return result;
}

// 19. 对象类型转换 - 将对象属性转换为指定类型
function convertPropertyTypes(obj, typeMap) {
    print.log("执行convertPropertyTypes函数 - 转换对象属性类型");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 类型映射: " + safeStringify(typeMap));
    if (obj == null || typeof obj !== 'object' || typeMap == null || typeof typeMap !== 'object') {
      print.log("- 结果: 参数无效,直接返回");
      return obj;
    }
   
    var result = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
            var value = obj;
            var type = typeMap;
            
            if (type && typeof type === 'function') {
                print.log("- 转换类型: " + key + " = " + safeStringify(value) + " -> " + safeStringify(type(value)));
                result = type(value);
            } else {
                result = value;
            }
      }
    }
    print.log("- 结果: 类型转换成功,对象变为: " + safeStringify(result));
    return result;
}

// 20. 对象属性验证 - 验证对象属性是否符合条件
function validateObject(obj, validations) {
    print.log("执行validateObject函数 - 验证对象属性");
    print.log("- 对象: " + safeStringify(obj));
    print.log("- 验证规则: " + safeStringify(validations));
    if (obj == null || typeof obj !== 'object' || validations == null || typeof validations !== 'object') {
      print.log("- 结果: 参数无效,返回验证失败");
      return {isValid: false, errors: []};
    }
   
    var errors = [];
   
    for (var key in validations) {
      if (validations.hasOwnProperty(key)) {
            var validator = validations;
            var value = obj;
            
            if (typeof validator === 'function') {
                if (!validator(value, key, obj)) {
                  errors.push({key: key, message: '属性验证失败', value: value});
                }
            } else if (validator.required && !obj.hasOwnProperty(key)) {
                errors.push({key: key, message: '属性必填', value: value});
            } else if (validator.type && typeof value !== validator.type) {
                errors.push({key: key, message: '属性类型错误', value: value});
            }
      }
    }
   
    print.log("- 结果: 验证" + (errors.length === 0 ? "通过" : "失败"));
    if (errors.length > 0) {
      print.log("- 错误信息: " + safeStringify(errors));
    }
    return {isValid: errors.length === 0, errors: errors};
}

// 使用示例 - 展示实际项目中的应用场景
function objectUtilsExample() {
    print.log("执行objectUtilsExample函数 - 对象工具函数示例");
    printl("=== 对象工具函数使用示例 ===");
   
    // 示例1: 安全获取嵌套属性 - 避免undefined错误
    printl("\n1. 安全获取嵌套属性:");
    var user = {
      name: "张三",
      contact: {
            email: "zhangsan@example.com"
      }
    };
    var phone = getSafe(user, "contact.phone", "未设置");
    var email = getSafe(user, "contact.email", "未设置");
    printl("   用户电话: " + phone);
    printl("   用户邮箱: " + email);
   
    // 示例2: 对象深度比较 - 验证数据一致性
    printl("\n2. 对象深度比较:");
    var serverData = {id: 1, name: "产品A", price: 100};
    var localData = {id: 1, name: "产品A", price: 100};
    var isSame = isEqual(serverData, localData);
    printl("   服务器数据: " + safeStringify(serverData));
    printl("   本地数据: " + safeStringify(localData));
    printl("   数据是否一致: " + (isSame ? "是" : "否"));
   
    // 示例3: 对象过滤 - 获取有效数据
    printl("\n3. 对象过滤:");
    var products = {
      "product1": {name: "手机", price: 2000, inStock: true},
      "product2": {name: "电脑", price: 5000, inStock: false},
      "product3": {name: "平板", price: 3000, inStock: true}
    };
    var availableProducts = filterObject(products, function(product) {
      return product.inStock && product.price < 4000;
    });
    printl("   库存充足且价格低于4000的产品: " + safeStringify(availableProducts));
   
    // 示例4: 对象属性更新 - 动态更新配置
    printl("\n4. 对象属性更新:");
    var config = {
      server: {
            host: "localhost",
            port: 8080
      },
      timeout: 3000
    };
    updateObject(config, "server.port", 9090);
    updateObject(config, "server.ssl", true);
    printl("   更新后的配置: " + safeStringify(config));
   
    // 示例5: 对象扁平化 - 便于存储和传输
    printl("\n5. 对象扁平化:");
    var nestedData = {
      user: {
            info: {
                name: "李四",
                age: 25
            },
            contact: {
                email: "lisi@example.com",
                phone: "13800138000"
            }
      }
    };
    var flatData = flattenObject(nestedData);
    printl("   扁平化数据: " + safeStringify(flatData));
   
    // 示例6: 对象验证 - 确保数据完整性
    printl("\n6. 对象验证:");
    var formData = {
      username: "testuser",
      password: "123",
      email: "invalid-email"
    };
    var validationRules = {
      username: {required: true, type: "string"},
      password: function(value) {
            return value.length >= 6;
      },
      email: function(value) {
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
      }
    };
    var validationResult = validateObject(formData, validationRules);
    printl("   验证结果: " + (validationResult.isValid ? "通过" : "失败"));
    if (!validationResult.isValid) {
      printl("   错误信息: " + safeStringify(validationResult.errors));
    }
   
    // 示例7: 对象类型转换 - 统一数据格式
    printl("\n7. 对象类型转换:");
    var apiData = {
      id: "123",
      price: "99.99",
      quantity: "10",
      isActive: "true"
    };
    var typeConversions = {
      id: parseInt,
      price: parseFloat,
      quantity: parseInt,
      isActive: function(value) { return value === "true"; }
    };
    var convertedData = convertPropertyTypes(apiData, typeConversions);
    printl("   转换前: " + safeStringify(apiData));
    printl("   转换后: " + safeStringify(convertedData));
    printl("   价格类型: " + (typeof convertedData.price));
    printl("   数量类型: " + (typeof convertedData.quantity));
    printl("   是否激活: " + convertedData.isActive);
}

// 可以通过调用这个函数来运行示例
print.log("准备执行示例函数");
objectUtilsExample();
print.log("示例函数执行完成");

// 实际项目应用示例 - 模拟AIWROK项目中的数据处理场景
function aiwrokProjectExample() {
    print.log("执行aiwrokProjectExample函数 - AIWROK项目应用示例");
    printl("\n=== AIWROK项目实际应用示例 ===");
   
    // 模拟从服务器获取的数据
    var serverResponse = {
      "code": 200,
      "message": "success",
      "data": {
            "userInfo": {
                "userId": "user_123456",
                "userName": "AIWROK用户",
                "userType": "normal",
                "createTime": "2023-12-25T10:30:00Z",
                "preferences": {
                  "theme": "dark",
                  "language": "zh-CN",
                  "notifications": true
                }
            },
            "deviceList": [
                {
                  "deviceId": "device_789",
                  "deviceName": "测试设备",
                  "status": "online",
                  "battery": "85",
                  "temperature": "25.5"
                }
            ]
      }
    };
   
    // 1. 安全获取用户信息
    var userInfo = getSafe(serverResponse, "data.userInfo", {});
    var userName = getSafe(userInfo, "userName", "未知用户");
    var userTheme = getSafe(userInfo, "preferences.theme", "light");
    printl("1. 用户信息获取:");
    printl("   用户名: " + userName);
    printl("   主题设置: " + userTheme);
   
    // 2. 处理设备数据
    var deviceList = getSafe(serverResponse, "data.deviceList", []);
    if (deviceList.length > 0) {
      var firstDevice = deviceList;
      
      // 转换设备属性类型
      var deviceData = convertPropertyTypes(firstDevice, {
            battery: parseInt,
            temperature: parseFloat
      });
      
      printl("\n2. 设备数据处理:");
      printl("   设备名称: " + deviceData.deviceName);
      printl("   设备状态: " + deviceData.status);
      printl("   电池电量: " + deviceData.battery + "%");
      printl("   设备温度: " + deviceData.temperature + "°C");
      
      // 检查设备状态
      if (deviceData.battery < 20) {
            printl("   警告: 电池电量低,需要充电!");
      }
      if (deviceData.temperature > 30) {
            printl("   警告: 设备温度过高!");
      }
    }
   
    // 3. 准备发送到服务器的请求数据
    var requestData = {
      userId: userInfo.userId,
      action: "update_preferences",
      timestamp: new Date().getTime(),
      data: {
            theme: "light",
            notifications: false
      }
    };
   
    // 验证请求数据
    var requestValidation = validateObject(requestData, {
      userId: {required: true, type: "string"},
      action: {required: true, type: "string"},
      timestamp: function(value) {
            return typeof value === "number" && value > 0;
      }
    });
   
    printl("\n3. 请求数据验证:");
    printl("   验证结果: " + (requestValidation.isValid ? "通过" : "失败"));
    if (requestValidation.isValid) {
      printl("   请求数据: " + safeStringify(requestData));
      // 在实际项目中,这里会调用okHttp等网络库发送请求
      // printl("   正在发送请求...");
    }
}

// 运行AIWROK项目应用示例
aiwrokProjectExample();






页: [1]
查看完整版本: AIWROK软件对象工具函数库例子