!15 Add: ObjectUtil中添加接口,是否为非法对象,可用于检测number、string、array、object等

Merge pull request !15 from hejiuri/develop
This commit is contained in:
dgflash
2025-08-17 04:57:41 +00:00
committed by Gitee
2 changed files with 41 additions and 1 deletions

View File

@@ -97,13 +97,32 @@ export class ArrayUtil {
}
/**
* 获取随机数组成员
* 获取数组中随机成员
* @param array 目标数组
*/
static getRandomValueInArray(array: any[]): any {
return array[Math.floor(Math.random() * array.length)];
}
/**
* 随机打乱数组
* @param array 目标数组
* @example [1,2,3,4,5] --> [5, 1, 2, 3, 4]
*/
static shuffleArray<T>(array: T[]): T[] {
// 创建一个原数组的副本
const newArr = [...array];
// 使用Fisher-Yates 洗牌算法打乱新数组
for (let i = newArr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[j]] = [newArr[j], newArr[i]];
}
// 返回打乱后的新数组
return newArr;
}
/**
* 获取连续数字数组, 范围在[start, end]之间
* @param start 开始数字

View File

@@ -60,4 +60,25 @@ export class ObjectUtil {
static copy(target: object): object {
return JSON.parse(JSON.stringify(target));
}
/**
* @function 检测是否为非法对象,比如"",null, undefined, NaN, [], {}
* @param {any} obj 任意基础数据对象number、string、array、object等
* @returns boolean 非法为trre, 否则为false
*/
static isIllegalObject(obj: any): boolean {
// 检查是否为空或未定义
if (obj == null || obj == undefined) return true;
// 检查是否是特殊值
if (obj === Infinity || obj === -Infinity) return true;
// 检测是否包含空格的字符串
if (typeof obj === "string" && obj.trim() === "") return true;
// 检查是否是无效的数字
if (Number.isNaN(obj)) return true;
// 检查是否是空数组
if (Array.isArray(obj) && obj.length <= 0) return true;
// 检查是否是空对象
if (typeof (obj) == "object" && Object.keys(obj).length <= 0) return true;
return false;
}
}