跳到主要内容

needArray()

function needArray<T>(value): ArrayType<T>[];

Defined in: array/needArray.ts:34

将任意值标准化为数组格式,提供一致的数组处理接口 处理规则:

  • 若输入已是数组,则直接返回原数组(不创建新数组)
  • 若输入为null/undefined,则返回空数组
  • 其他任何类型的值均包装为单元素数组

Type Parameters

Type ParameterDefault typeDescription
Tany输入值的类型,可以是任意类型(包括数组)

Parameters

ParameterTypeDescription
valueT需要标准化为数组的值

Returns

ArrayType<T>[]

标准化后的数组

  • 当T为数组类型时,返回T本身
  • 当T为null/undefined时,返回空数组
  • 其他情况返回包含value的单元素数组

Example

needArray(5);          // 返回 [5](基本类型包装)
needArray([1, 2, 3]); // 返回 [1, 2, 3](数组直接返回)
needArray(null); // 返回 [](null处理)
needArray(undefined); // 返回 [](undefined处理)
needArray('hello'); // 返回 ['hello'](字符串包装)
needArray({ a: 1 }); // 返回 [{ a: 1 }](对象包装)
needArray(true); // 返回 [true](布尔值包装)
needArray(new Date()); // 返回 [Date实例](特殊对象包装)

See

ArrayType - 用于提取数组元素类型的工具类型,定义为:type ArrayType<T = any> = T extends Array<infer R> ? R : T Note: 使用isNil函数判断null/undefined,该函数来自'../types'模块 Note: 对于数组输入,返回原数组引用而非副本,修改返回值会影响原数组 Note: 不处理类数组对象(如arguments、NodeList),会将其视为普通对象包装为单元素数组