自动发帖软件

标题: AIWROK软件对象工具函数库例子 [打印本页]

作者: 发帖软件    时间: 3 小时前
标题: AIWROK软件对象工具函数库例子
AIWROK软件对象工具函数库例子


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

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

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

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

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

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

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

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

  24. // 合并对象 - 将多个对象合并为一个新对象
  25. function mergeObjects() {
  26.     print.log("执行mergeObjects函数 - 合并多个对象");
  27.     var target = {};
  28.     var i, source;
  29.    
  30.     for (i = 0; i < arguments.length; i++) {
  31.         source = arguments[i];
  32.         print.log("  - 合并第" + (i + 1) + "个对象: " + safeStringify(source));
  33.         if (source != null && typeof source === 'object') {
  34.             for (var key in source) {
  35.                 if (source.hasOwnProperty(key)) {
  36.                     target[key] = source[key];
  37.                 }
  38.             }
  39.         }
  40.     }
  41.    
  42.     print.log("  - 合并结果: " + safeStringify(target));
  43.     print.log("  - 结果: 拷贝成功,目标对象变为: " + safeStringify(target));
  44.     return target;
  45. }

  46. // 获取对象键值对 - 返回[[key1, value1], [key2, value2], ...]格式数组
  47. function getObjectEntries(obj) {
  48.     print.log("执行getObjectEntries函数 - 获取对象键值对");
  49.     print.log("  - 对象: " + safeStringify(obj));
  50.     var entries = [];
  51.     var key;
  52.    
  53.     if (obj != null && typeof obj === 'object') {
  54.         for (key in obj) {
  55.             if (obj.hasOwnProperty(key)) {
  56.                 entries.push([key, obj[key]]);
  57.             }
  58.         }
  59.     }
  60.    
  61.     print.log("  - 结果: " + safeStringify(entries));
  62.     return entries;
  63. }

  64. // 获取对象键数组
  65. function getObjectKeys(obj) {
  66.     print.log("执行getObjectKeys函数 - 获取对象键数组");
  67.     print.log("  - 对象: " + safeStringify(obj));
  68.     var keys = [];
  69.     var key;
  70.    
  71.     if (obj != null && typeof obj === 'object') {
  72.         for (key in obj) {
  73.             if (obj.hasOwnProperty(key)) {
  74.                 keys.push(key);
  75.             }
  76.         }
  77.     }
  78.    
  79.     print.log("  - 结果: " + safeStringify(keys));
  80.     return keys;
  81. }

  82. // 获取对象值数组
  83. function getObjectValues(obj) {
  84.     print.log("执行getObjectValues函数 - 获取对象值数组");
  85.     print.log("  - 对象: " + safeStringify(obj));
  86.     var values = [];
  87.     var key;
  88.    
  89.     if (obj != null && typeof obj === 'object') {
  90.         for (key in obj) {
  91.             if (obj.hasOwnProperty(key)) {
  92.                 values.push(obj[key]);
  93.             }
  94.         }
  95.     }
  96.    
  97.     print.log("  - 结果: " + safeStringify(values));
  98.     return values;
  99. }

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

  113. // 检查对象是否被冻结
  114. function isObjectFrozen(obj) {
  115.     print.log("执行isObjectFrozen函数 - 检查对象是否被冻结");
  116.     print.log("  - 对象: " + safeStringify(obj));
  117.     var result;
  118.     if (obj != null && typeof obj === 'object') {
  119.         result = Object.isFrozen(obj);
  120.     } else {
  121.         result = false;
  122.     }
  123.     print.log("  - 结果: " + (result ? "对象已被冻结" : "对象未被冻结"));
  124.     print.log("  - 结果: " + safeStringify(result));
  125.     print.log("  - 结果: " + safeStringify(result));
  126.     print.log("  - 结果: 转换成功");
  127.     print.log("  - 结果: 扁平化成功,扁平对象: " + safeStringify(result));
  128.     return result;
  129. }

  130. // 深度克隆对象 - 支持嵌套对象和数组
  131. function deepCloneObject(obj) {
  132.     print.log("执行deepCloneObject函数 - 深度克隆对象");
  133.     print.log("  - 对象: " + safeStringify(obj));
  134.     var clone;
  135.     var i, key;
  136.    
  137.     if (obj == null || typeof obj !== 'object') {
  138.         print.log("  - 结果: 对象为null或非对象类型,直接返回");
  139.         return obj;
  140.     }
  141.    
  142.     // 处理数组
  143.     if (obj instanceof Array) {
  144.         clone = [];
  145.         for (i = 0; i < obj.length; i++) {
  146.             clone[i] = deepCloneObject(obj[i]);
  147.         }
  148.     }
  149.     // 处理对象
  150.     else {
  151.         clone = {};
  152.         for (key in obj) {
  153.             if (obj.hasOwnProperty(key)) {
  154.                 clone[key] = deepCloneObject(obj[key]);
  155.             }
  156.         }
  157.     }
  158.    
  159.     print.log("  - 结果: 克隆成功");
  160.     return clone;
  161. }

  162. // 1. 对象属性安全获取 - 避免undefined错误
  163. function getSafe(obj, path, defaultValue) {
  164.     print.log("执行getSafe函数 - 安全获取对象属性");
  165.     print.log("  - 对象: " + safeStringify(obj));
  166.     print.log("  - 路径: " + path);
  167.    
  168.     if (obj == null) {
  169.         print.log("  - 结果: 对象为null,返回默认值: " + defaultValue);
  170.         return defaultValue;
  171.     }
  172.    
  173.     var keys = path.split('.');
  174.     var current = obj;
  175.    
  176.     for (var i = 0; i < keys.length; i++) {
  177.         if (current == null || !current.hasOwnProperty(keys[i])) {
  178.             print.log("  - 结果: 路径不存在,返回默认值: " + defaultValue);
  179.             return defaultValue;
  180.         }
  181.         current = current[keys[i]];
  182.     }
  183.    
  184.     print.log("  - 结果: 获取成功,值为: " + safeStringify(current));
  185.     return current;
  186. }

  187. // 2. 对象比较 - 深度比较两个对象是否相等
  188. function isEqual(obj1, obj2) {
  189.     print.log("执行isEqual函数 - 深度比较两个对象是否相等");
  190.     print.log("  - 对象1: " + safeStringify(obj1));
  191.     print.log("  - 对象2: " + safeStringify(obj2));
  192.     if (obj1 === obj2) {
  193.         print.log("  - 结果: 对象引用相同,直接返回true");
  194.         print.log("  - 结果: 对象深度比较,相等");
  195.     return true;
  196.     }
  197.    
  198.     if (obj1 == null || obj2 == null) {
  199.         print.log("  - 结果: 其中一个对象为null,返回false");
  200.         return false;
  201.     }
  202.    
  203.     if (typeof obj1 !== typeof obj2) {
  204.         print.log("  - 结果: 对象类型不同,返回false");
  205.         return false;
  206.     }
  207.    
  208.     if (typeof obj1 !== 'object') {
  209.         var result = obj1 === obj2;
  210.         print.log("  - 结果: 基础类型比较," + (result ? "相等" : "不相等"));
  211.         return result;
  212.     }
  213.    
  214.     if (obj1 instanceof Array && obj2 instanceof Array) {
  215.         if (obj1.length !== obj2.length) return false;
  216.         for (var i = 0; i < obj1.length; i++) {
  217.             if (!isEqual(obj1[i], obj2[i])) return false;
  218.         }
  219.         return true;
  220.     }
  221.    
  222.     if (obj1 instanceof Array || obj2 instanceof Array) return false;
  223.    
  224.     var keys1 = getObjectKeys(obj1);
  225.     var keys2 = getObjectKeys(obj2);
  226.    
  227.     if (keys1.length !== keys2.length) return false;
  228.    
  229.     for (var j = 0; j < keys1.length; j++) {
  230.         var key = keys1[j];
  231.         if (!obj2.hasOwnProperty(key) || !isEqual(obj1[key], obj2[key])) {
  232.             return false;
  233.         }
  234.     }
  235.    
  236.     return true;
  237. }

  238. // 3. 对象过滤 - 保留符合条件的属性
  239. function filterObject(obj, predicate) {
  240.     print.log("执行filterObject函数 - 过滤对象属性");
  241.     print.log("  - 对象: " + safeStringify(obj));
  242.     print.log("  - 过滤条件: " + predicate.toString());
  243.     if (obj == null || typeof obj !== 'object' || typeof predicate !== 'function') {
  244.         print.log("  - 结果: 参数无效,返回空对象");
  245.         return {};
  246.     }
  247.    
  248.     var result = {};
  249.     for (var key in obj) {
  250.         if (obj.hasOwnProperty(key) && predicate(obj[key], key, obj)) {
  251.             result[key] = obj[key];
  252.         }
  253.     }
  254.     return result;
  255. }

  256. // 4. 对象转换为Map - 适合需要键值对操作的场景
  257. function objectToMap(obj) {
  258.     print.log("执行objectToMap函数 - 对象转换为Map");
  259.     print.log("  - 对象: " + safeStringify(obj));
  260.     if (obj == null || typeof obj !== 'object') {
  261.         print.log("  - 结果: 对象为null或非对象类型,返回空Map");
  262.         return new HashMap();
  263.     }
  264.    
  265.     var map = new HashMap();
  266.     for (var key in obj) {
  267.         if (obj.hasOwnProperty(key)) {
  268.             map.put(key, obj[key]);
  269.         }
  270.     }
  271.     print.log("  - 结果: 转换成功,Map大小: " + map.size());
  272.     return map;
  273. }

  274. // 5. Map转换为对象
  275. function mapToObject(map) {
  276.     print.log("执行mapToObject函数 - Map转换为对象");
  277.     print.log("  - Map: " + map.toString());
  278.     if (map == null || typeof map !== 'object' || typeof map.entrySet !== 'function') {
  279.         print.log("  - 结果: Map无效,返回空对象");
  280.         return {};
  281.     }
  282.    
  283.     var obj = {};
  284.     var entries = map.entrySet().toArray();
  285.     for (var i = 0; i < entries.length; i++) {
  286.         var entry = entries[i];
  287.         obj[entry.getKey()] = entry.getValue();
  288.     }
  289.     return obj;
  290. }

  291. // 6. 对象属性遍历 - 对每个属性执行回调函数
  292. function forEachObject(obj, callback) {
  293.     print.log("执行forEachObject函数 - 遍历对象属性");
  294.     print.log("  - 对象: " + safeStringify(obj));
  295.     print.log("  - 回调函数: " + callback.toString());
  296.     if (obj == null || typeof obj !== 'object' || typeof callback !== 'function') {
  297.         print.log("  - 结果: 参数无效,直接返回");
  298.         return;
  299.     }
  300.    
  301.     for (var key in obj) {
  302.         if (obj.hasOwnProperty(key)) {
  303.             print.log("  - 处理属性: " + key + " = " + safeStringify(obj[key]));
  304.             callback(obj[key], key, obj);
  305.         }
  306.     }
  307.     print.log("  - 结果: 遍历完成");
  308. }

  309. // 7. 对象属性转换 - 转换对象的属性值
  310. function transformObject(obj, transformer) {
  311.     print.log("执行transformObject函数 - 转换对象属性值");
  312.     print.log("  - 对象: " + safeStringify(obj));
  313.     print.log("  - 转换函数: " + transformer.toString());
  314.     if (obj == null || typeof obj !== 'object' || typeof transformer !== 'function') {
  315.         print.log("  - 结果: 参数无效,返回空对象");
  316.         return {};
  317.     }
  318.    
  319.     var result = {};
  320.     for (var key in obj) {
  321.         if (obj.hasOwnProperty(key)) {
  322.             result[key] = transformer(obj[key], key, obj);
  323.         }
  324.     }
  325.     return result;
  326. }

  327. // 8. 检查对象是否包含指定属性
  328. function hasOwnProperty(obj, key) {
  329.     print.log("执行hasOwnProperty函数 - 检查对象属性是否存在");
  330.     print.log("  - 对象: " + safeStringify(obj));
  331.     print.log("  - 属性: " + key);
  332.     var result;
  333.     if (obj == null || typeof obj !== 'object') {
  334.         result = false;
  335.     } else {
  336.         result = obj.hasOwnProperty(key);
  337.     }
  338.     print.log("  - 结果: " + (result ? "存在" : "不存在"));
  339.     return result;
  340. }

  341. // 9. 获取对象大小(属性数量)
  342. function getObjectSize(obj) {
  343.     print.log("执行getObjectSize函数 - 获取对象属性数量");
  344.     print.log("  - 对象: " + safeStringify(obj));
  345.     var count = 0;
  346.     if (obj == null || typeof obj !== 'object') {
  347.         count = 0;
  348.     } else {
  349.         for (var key in obj) {
  350.             if (obj.hasOwnProperty(key)) count++;
  351.         }
  352.     }
  353.     print.log("  - 结果: 属性数量为" + count);
  354.     return count;
  355. }

  356. // 10. 对象序列化增强 - 处理循环引用和特殊类型
  357. function safeStringify(obj, space) {
  358.     print.log("执行safeStringify函数 - 对象序列化");
  359.     try {
  360.         var cache = [];
  361.         var result = JSON.stringify(obj, function(key, value) {
  362.             if (typeof value === 'object' && value !== null) {
  363.                 if (cache.indexOf(value) !== -1) {
  364.                     return '[Circular Reference]';
  365.                 }
  366.                 cache.push(value);
  367.             }
  368.             return value;
  369.         }, space);
  370.         cache = null; // 释放内存
  371.         return result;
  372.     } catch (e) {
  373.         print.log("  - 结果: 序列化失败,返回空对象字符串");
  374.         return '{}';
  375.     }
  376. }

  377. // 11. 对象属性更新 - 安全更新对象属性,支持嵌套路径
  378. function updateObject(obj, path, value) {
  379.     print.log("执行updateObject函数 - 更新对象属性");
  380.     print.log("  - 对象: " + safeStringify(obj));
  381.     print.log("  - 路径: " + path);
  382.     print.log("  - 新值: " + safeStringify(value));
  383.     if (obj == null || typeof obj !== 'object') {
  384.         print.log("  - 结果: 对象为null或非对象类型,直接返回");
  385.         return obj;
  386.     }
  387.    
  388.     var keys = path.split('.');
  389.     var current = obj;
  390.    
  391.     for (var i = 0; i < keys.length - 1; i++) {
  392.         var key = keys[i];
  393.         if (!current[key] || typeof current[key] !== 'object') {
  394.             current[key] = {};
  395.         }
  396.         current = current[key];
  397.     }
  398.    
  399.     current[keys[keys.length - 1]] = value;
  400.     print.log("  - 结果: 更新成功,对象变为: " + safeStringify(obj));
  401.     return obj;
  402. }

  403. // 12. 对象属性删除 - 安全删除对象属性,支持嵌套路径
  404. function deleteProperty(obj, path) {
  405.     print.log("执行deleteProperty函数 - 删除对象属性");
  406.     print.log("  - 对象: " + safeStringify(obj));
  407.     print.log("  - 路径: " + path);
  408.     if (obj == null || typeof obj !== 'object') {
  409.         print.log("  - 结果: 对象为null或非对象类型,直接返回");
  410.         return obj;
  411.     }
  412.    
  413.     var keys = path.split('.');
  414.     var current = obj;
  415.    
  416.     for (var i = 0; i < keys.length - 1; i++) {
  417.         var key = keys[i];
  418.         if (!current[key] || typeof current[key] !== 'object') {
  419.             print.log("  - 结果: 路径不存在,直接返回原对象");
  420.             return obj;
  421.         }
  422.         current = current[key];
  423.     }
  424.    
  425.     delete current[keys[keys.length - 1]];
  426.     print.log("  - 结果: 删除成功,对象变为: " + safeStringify(obj));
  427.     return obj;
  428. }

  429. // 13. 对象属性遍历并转换 - 深度转换对象的所有属性
  430. function deepTransform(obj, transformer) {
  431.     print.log("执行deepTransform函数 - 深度转换对象属性");
  432.     print.log("  - 对象: " + safeStringify(obj));
  433.     print.log("  - 转换函数: " + transformer.toString());
  434.     if (obj == null || typeof obj !== 'object' || typeof transformer !== 'function') {
  435.         print.log("  - 结果: 参数无效,直接返回");
  436.         return obj;
  437.     }
  438.    
  439.     if (obj instanceof Array) {
  440.         return obj.map(function(item) {
  441.             return deepTransform(item, transformer);
  442.         });
  443.     }
  444.    
  445.     var result = {};
  446.     for (var key in obj) {
  447.         if (obj.hasOwnProperty(key)) {
  448.             var value = obj[key];
  449.             if (typeof value === 'object' && value !== null) {
  450.                 result[key] = deepTransform(value, transformer);
  451.             } else {
  452.                 result[key] = transformer(value, key, obj);
  453.             }
  454.         }
  455.     }
  456.     return result;
  457. }

  458. // 14. 对象扁平化 - 将嵌套对象转换为扁平结构
  459. function flattenObject(obj, prefix) {
  460.     print.log("执行flattenObject函数 - 扁平化嵌套对象");
  461.     print.log("  - 嵌套对象: " + safeStringify(obj));
  462.     if (obj == null || typeof obj !== 'object') {
  463.         print.log("  - 结果: 参数无效,直接返回");
  464.         return obj;
  465.     }
  466.    
  467.     var result = {};
  468.     prefix = prefix || '';
  469.    
  470.     for (var key in obj) {
  471.         if (obj.hasOwnProperty(key)) {
  472.             var fullPath = prefix ? prefix + '.' + key : key;
  473.             var value = obj[key];
  474.             
  475.             if (typeof value === 'object' && value !== null && !(value instanceof Array)) {
  476.                 var flatChild = flattenObject(value, fullPath);
  477.                 for (var childKey in flatChild) {
  478.                     if (flatChild.hasOwnProperty(childKey)) {
  479.                         result[childKey] = flatChild[childKey];
  480.                     }
  481.                 }
  482.             } else {
  483.                 result[fullPath] = value;
  484.             }
  485.         }
  486.     }
  487.     return result;
  488. }

  489. // 15. 扁平对象还原 - 将扁平结构转换为嵌套对象
  490. function unflattenObject(flatObj) {
  491.     print.log("执行unflattenObject函数 - 还原扁平对象");
  492.     print.log("  - 扁平对象: " + safeStringify(flatObj));
  493.     if (flatObj == null || typeof flatObj !== 'object') {
  494.         print.log("  - 结果: 参数无效,直接返回");
  495.         return flatObj;
  496.     }
  497.    
  498.     var result = {};
  499.    
  500.     for (var key in flatObj) {
  501.         if (flatObj.hasOwnProperty(key)) {
  502.             print.log("  - 还原属性: " + key + " = " + safeStringify(flatObj[key]));
  503.             updateObject(result, key, flatObj[key]);
  504.         }
  505.     }
  506.     print.log("  - 结果: 还原成功,嵌套对象: " + safeStringify(result));
  507.     return result;
  508. }

  509. // 16. 对象属性存在性检查 - 检查嵌套属性是否存在
  510. function hasNestedProperty(obj, path) {
  511.     print.log("执行hasNestedProperty函数 - 检查嵌套属性是否存在");
  512.     print.log("  - 对象: " + safeStringify(obj));
  513.     print.log("  - 路径: " + path);
  514.     if (obj == null || typeof obj !== 'object') {
  515.         print.log("  - 结果: 对象为null或非对象类型,返回false");
  516.         return false;
  517.     }
  518.    
  519.     var keys = path.split('.');
  520.     var current = obj;
  521.    
  522.     for (var i = 0; i < keys.length; i++) {
  523.         var key = keys[i];
  524.         if (!current.hasOwnProperty(key)) {
  525.             print.log("  - 结果: 路径" + keys.slice(0, i + 1).join('.') + "不存在,返回false");
  526.             return false;
  527.         }
  528.         current = current[key];
  529.     }
  530.     print.log("  - 结果: 路径存在");
  531.     return true;
  532. }

  533. // 17. 对象属性拷贝 - 从一个对象拷贝属性到另一个对象
  534. function copyProperties(source, target, properties) {
  535.     print.log("执行copyProperties函数 - 拷贝对象属性");
  536.     print.log("  - 源对象: " + safeStringify(source));
  537.     print.log("  - 目标对象: " + safeStringify(target));
  538.     print.log("  - 指定属性: " + safeStringify(properties));
  539.     if (source == null || typeof source !== 'object' || target == null || typeof target !== 'object') {
  540.         print.log("  - 结果: 参数无效,返回目标对象");
  541.         return target;
  542.     }
  543.    
  544.     if (!properties || !(properties instanceof Array)) {
  545.         // 拷贝所有属性
  546.         for (var key in source) {
  547.             if (source.hasOwnProperty(key)) {
  548.                 target[key] = source[key];
  549.             }
  550.         }
  551.     } else {
  552.         // 只拷贝指定属性
  553.         for (var i = 0; i < properties.length; i++) {
  554.             var key = properties[i];
  555.             if (source.hasOwnProperty(key)) {
  556.                 target[key] = source[key];
  557.             }
  558.         }
  559.     }
  560.     return target;
  561. }

  562. // 18. 对象属性重命名 - 重命名对象的属性
  563. function renameProperties(obj, mapping) {
  564.     print.log("执行renameProperties函数 - 重命名对象属性");
  565.     print.log("  - 对象: " + safeStringify(obj));
  566.     print.log("  - 映射关系: " + safeStringify(mapping));
  567.     if (obj == null || typeof obj !== 'object' || mapping == null || typeof mapping !== 'object') {
  568.         print.log("  - 结果: 参数无效,直接返回");
  569.         return obj;
  570.     }
  571.    
  572.     var result = {};
  573.     for (var key in obj) {
  574.         if (obj.hasOwnProperty(key)) {
  575.             var newKey = mapping[key] || key;
  576.             print.log("  - 重命名: " + key + " -> " + newKey + " = " + safeStringify(obj[key]));
  577.             result[newKey] = obj[key];
  578.         }
  579.     }
  580.     print.log("  - 结果: 重命名成功,对象变为: " + safeStringify(result));
  581.     return result;
  582. }

  583. // 19. 对象类型转换 - 将对象属性转换为指定类型
  584. function convertPropertyTypes(obj, typeMap) {
  585.     print.log("执行convertPropertyTypes函数 - 转换对象属性类型");
  586.     print.log("  - 对象: " + safeStringify(obj));
  587.     print.log("  - 类型映射: " + safeStringify(typeMap));
  588.     if (obj == null || typeof obj !== 'object' || typeMap == null || typeof typeMap !== 'object') {
  589.         print.log("  - 结果: 参数无效,直接返回");
  590.         return obj;
  591.     }
  592.    
  593.     var result = {};
  594.     for (var key in obj) {
  595.         if (obj.hasOwnProperty(key)) {
  596.             var value = obj[key];
  597.             var type = typeMap[key];
  598.             
  599.             if (type && typeof type === 'function') {
  600.                 print.log("  - 转换类型: " + key + " = " + safeStringify(value) + " -> " + safeStringify(type(value)));
  601.                 result[key] = type(value);
  602.             } else {
  603.                 result[key] = value;
  604.             }
  605.         }
  606.     }
  607.     print.log("  - 结果: 类型转换成功,对象变为: " + safeStringify(result));
  608.     return result;
  609. }

  610. // 20. 对象属性验证 - 验证对象属性是否符合条件
  611. function validateObject(obj, validations) {
  612.     print.log("执行validateObject函数 - 验证对象属性");
  613.     print.log("  - 对象: " + safeStringify(obj));
  614.     print.log("  - 验证规则: " + safeStringify(validations));
  615.     if (obj == null || typeof obj !== 'object' || validations == null || typeof validations !== 'object') {
  616.         print.log("  - 结果: 参数无效,返回验证失败");
  617.         return {isValid: false, errors: []};
  618.     }
  619.    
  620.     var errors = [];
  621.    
  622.     for (var key in validations) {
  623.         if (validations.hasOwnProperty(key)) {
  624.             var validator = validations[key];
  625.             var value = obj[key];
  626.             
  627.             if (typeof validator === 'function') {
  628.                 if (!validator(value, key, obj)) {
  629.                     errors.push({key: key, message: '属性验证失败', value: value});
  630.                 }
  631.             } else if (validator.required && !obj.hasOwnProperty(key)) {
  632.                 errors.push({key: key, message: '属性必填', value: value});
  633.             } else if (validator.type && typeof value !== validator.type) {
  634.                 errors.push({key: key, message: '属性类型错误', value: value});
  635.             }
  636.         }
  637.     }
  638.    
  639.     print.log("  - 结果: 验证" + (errors.length === 0 ? "通过" : "失败"));
  640.     if (errors.length > 0) {
  641.         print.log("  - 错误信息: " + safeStringify(errors));
  642.     }
  643.     return {isValid: errors.length === 0, errors: errors};
  644. }

  645. // 使用示例 - 展示实际项目中的应用场景
  646. function objectUtilsExample() {
  647.     print.log("执行objectUtilsExample函数 - 对象工具函数示例");
  648.     printl("=== 对象工具函数使用示例 ===");
  649.    
  650.     // 示例1: 安全获取嵌套属性 - 避免undefined错误
  651.     printl("\n1. 安全获取嵌套属性:");
  652.     var user = {
  653.         name: "张三",
  654.         contact: {
  655.             email: "zhangsan@example.com"
  656.         }
  657.     };
  658.     var phone = getSafe(user, "contact.phone", "未设置");
  659.     var email = getSafe(user, "contact.email", "未设置");
  660.     printl("   用户电话: " + phone);
  661.     printl("   用户邮箱: " + email);
  662.    
  663.     // 示例2: 对象深度比较 - 验证数据一致性
  664.     printl("\n2. 对象深度比较:");
  665.     var serverData = {id: 1, name: "产品A", price: 100};
  666.     var localData = {id: 1, name: "产品A", price: 100};
  667.     var isSame = isEqual(serverData, localData);
  668.     printl("   服务器数据: " + safeStringify(serverData));
  669.     printl("   本地数据: " + safeStringify(localData));
  670.     printl("   数据是否一致: " + (isSame ? "是" : "否"));
  671.    
  672.     // 示例3: 对象过滤 - 获取有效数据
  673.     printl("\n3. 对象过滤:");
  674.     var products = {
  675.         "product1": {name: "手机", price: 2000, inStock: true},
  676.         "product2": {name: "电脑", price: 5000, inStock: false},
  677.         "product3": {name: "平板", price: 3000, inStock: true}
  678.     };
  679.     var availableProducts = filterObject(products, function(product) {
  680.         return product.inStock && product.price < 4000;
  681.     });
  682.     printl("   库存充足且价格低于4000的产品: " + safeStringify(availableProducts));
  683.    
  684.     // 示例4: 对象属性更新 - 动态更新配置
  685.     printl("\n4. 对象属性更新:");
  686.     var config = {
  687.         server: {
  688.             host: "localhost",
  689.             port: 8080
  690.         },
  691.         timeout: 3000
  692.     };
  693.     updateObject(config, "server.port", 9090);
  694.     updateObject(config, "server.ssl", true);
  695.     printl("   更新后的配置: " + safeStringify(config));
  696.    
  697.     // 示例5: 对象扁平化 - 便于存储和传输
  698.     printl("\n5. 对象扁平化:");
  699.     var nestedData = {
  700.         user: {
  701.             info: {
  702.                 name: "李四",
  703.                 age: 25
  704.             },
  705.             contact: {
  706.                 email: "lisi@example.com",
  707.                 phone: "13800138000"
  708.             }
  709.         }
  710.     };
  711.     var flatData = flattenObject(nestedData);
  712.     printl("   扁平化数据: " + safeStringify(flatData));
  713.    
  714.     // 示例6: 对象验证 - 确保数据完整性
  715.     printl("\n6. 对象验证:");
  716.     var formData = {
  717.         username: "testuser",
  718.         password: "123",
  719.         email: "invalid-email"
  720.     };
  721.     var validationRules = {
  722.         username: {required: true, type: "string"},
  723.         password: function(value) {
  724.             return value.length >= 6;
  725.         },
  726.         email: function(value) {
  727.             return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
  728.         }
  729.     };
  730.     var validationResult = validateObject(formData, validationRules);
  731.     printl("   验证结果: " + (validationResult.isValid ? "通过" : "失败"));
  732.     if (!validationResult.isValid) {
  733.         printl("   错误信息: " + safeStringify(validationResult.errors));
  734.     }
  735.    
  736.     // 示例7: 对象类型转换 - 统一数据格式
  737.     printl("\n7. 对象类型转换:");
  738.     var apiData = {
  739.         id: "123",
  740.         price: "99.99",
  741.         quantity: "10",
  742.         isActive: "true"
  743.     };
  744.     var typeConversions = {
  745.         id: parseInt,
  746.         price: parseFloat,
  747.         quantity: parseInt,
  748.         isActive: function(value) { return value === "true"; }
  749.     };
  750.     var convertedData = convertPropertyTypes(apiData, typeConversions);
  751.     printl("   转换前: " + safeStringify(apiData));
  752.     printl("   转换后: " + safeStringify(convertedData));
  753.     printl("   价格类型: " + (typeof convertedData.price));
  754.     printl("   数量类型: " + (typeof convertedData.quantity));
  755.     printl("   是否激活: " + convertedData.isActive);
  756. }

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

  761. // 实际项目应用示例 - 模拟AIWROK项目中的数据处理场景
  762. function aiwrokProjectExample() {
  763.     print.log("执行aiwrokProjectExample函数 - AIWROK项目应用示例");
  764.     printl("\n=== AIWROK项目实际应用示例 ===");
  765.    
  766.     // 模拟从服务器获取的数据
  767.     var serverResponse = {
  768.         "code": 200,
  769.         "message": "success",
  770.         "data": {
  771.             "userInfo": {
  772.                 "userId": "user_123456",
  773.                 "userName": "AIWROK用户",
  774.                 "userType": "normal",
  775.                 "createTime": "2023-12-25T10:30:00Z",
  776.                 "preferences": {
  777.                     "theme": "dark",
  778.                     "language": "zh-CN",
  779.                     "notifications": true
  780.                 }
  781.             },
  782.             "deviceList": [
  783.                 {
  784.                     "deviceId": "device_789",
  785.                     "deviceName": "测试设备",
  786.                     "status": "online",
  787.                     "battery": "85",
  788.                     "temperature": "25.5"
  789.                 }
  790.             ]
  791.         }
  792.     };
  793.    
  794.     // 1. 安全获取用户信息
  795.     var userInfo = getSafe(serverResponse, "data.userInfo", {});
  796.     var userName = getSafe(userInfo, "userName", "未知用户");
  797.     var userTheme = getSafe(userInfo, "preferences.theme", "light");
  798.     printl("1. 用户信息获取:");
  799.     printl("   用户名: " + userName);
  800.     printl("   主题设置: " + userTheme);
  801.    
  802.     // 2. 处理设备数据
  803.     var deviceList = getSafe(serverResponse, "data.deviceList", []);
  804.     if (deviceList.length > 0) {
  805.         var firstDevice = deviceList[0];
  806.         
  807.         // 转换设备属性类型
  808.         var deviceData = convertPropertyTypes(firstDevice, {
  809.             battery: parseInt,
  810.             temperature: parseFloat
  811.         });
  812.         
  813.         printl("\n2. 设备数据处理:");
  814.         printl("   设备名称: " + deviceData.deviceName);
  815.         printl("   设备状态: " + deviceData.status);
  816.         printl("   电池电量: " + deviceData.battery + "%");
  817.         printl("   设备温度: " + deviceData.temperature + "°C");
  818.         
  819.         // 检查设备状态
  820.         if (deviceData.battery < 20) {
  821.             printl("   警告: 电池电量低,需要充电!");
  822.         }
  823.         if (deviceData.temperature > 30) {
  824.             printl("   警告: 设备温度过高!");
  825.         }
  826.     }
  827.    
  828.     // 3. 准备发送到服务器的请求数据
  829.     var requestData = {
  830.         userId: userInfo.userId,
  831.         action: "update_preferences",
  832.         timestamp: new Date().getTime(),
  833.         data: {
  834.             theme: "light",
  835.             notifications: false
  836.         }
  837.     };
  838.    
  839.     // 验证请求数据
  840.     var requestValidation = validateObject(requestData, {
  841.         userId: {required: true, type: "string"},
  842.         action: {required: true, type: "string"},
  843.         timestamp: function(value) {
  844.             return typeof value === "number" && value > 0;
  845.         }
  846.     });
  847.    
  848.     printl("\n3. 请求数据验证:");
  849.     printl("   验证结果: " + (requestValidation.isValid ? "通过" : "失败"));
  850.     if (requestValidation.isValid) {
  851.         printl("   请求数据: " + safeStringify(requestData));
  852.         // 在实际项目中,这里会调用okHttp等网络库发送请求
  853.         // printl("   正在发送请求...");
  854.     }
  855. }

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




复制代码







欢迎光临 自动发帖软件 (http://www.fatiegongju.com/) Powered by Discuz! X3.2