Skip to content

list

列表操作函数。

创建一个指定长度的数组,并用指定的值填充。

基础用法

typescript
import { list } from 'radash'

// 创建长度为5的数组,用0填充
const zeros = list(5, 0)
// [0, 0, 0, 0, 0]

// 创建长度为3的数组,用'hello'填充
const greetings = list(3, 'hello')
// ['hello', 'hello', 'hello']

语法

typescript
function list<T>(
  length: number,
  value: T
): T[]

参数

  • length (number): 要创建的数组长度
  • value (T): 用于填充数组的值

返回值

返回一个指定长度的数组,所有元素都等于指定的值。

示例

创建数字数组

typescript
import { list } from 'radash'

// 创建5个1
const ones = list(5, 1)
// [1, 1, 1, 1, 1]

// 创建10个0
const zeros = list(10, 0)
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

// 创建3个-1
const negatives = list(3, -1)
// [-1, -1, -1]

创建字符串数组

typescript
import { list } from 'radash'

// 创建4个空字符串
const emptyStrings = list(4, '')
// ['', '', '', '']

// 创建3个'placeholder'
const placeholders = list(3, 'placeholder')
// ['placeholder', 'placeholder', 'placeholder']

// 创建2个'*'
const stars = list(2, '*')
// ['*', '*']

创建对象数组

typescript
import { list } from 'radash'

// 创建3个空对象
const emptyObjects = list(3, {})
// [{}, {}, {}]

// 创建2个默认用户对象
const defaultUser = { id: 0, name: '', age: 0 }
const users = list(2, defaultUser)
// [
//   { id: 0, name: '', age: 0 },
//   { id: 0, name: '', age: 0 }
// ]

创建布尔数组

typescript
import { list } from 'radash'

// 创建5个true
const trues = list(5, true)
// [true, true, true, true, true]

// 创建3个false
const falses = list(3, false)
// [false, false, false]

创建数组数组

typescript
import { list } from 'radash'

// 创建3个空数组
const emptyArrays = list(3, [])
// [[], [], []]

// 创建2个默认数组
const defaultArray = [1, 2, 3]
const arrays = list(2, defaultArray)
// [[1, 2, 3], [1, 2, 3]]

创建null或undefined数组

typescript
import { list } from 'radash'

// 创建4个null
const nulls = list(4, null)
// [null, null, null, null]

// 创建3个undefined
const undefineds = list(3, undefined)
// [undefined, undefined, undefined]

与map结合使用

typescript
import { list } from 'radash'

// 创建索引数组
const indices = list(5, 0).map((_, index) => index)
// [0, 1, 2, 3, 4]

// 创建偶数数组
const evens = list(5, 0).map((_, index) => index * 2)
// [0, 2, 4, 6, 8]

// 创建字母数组
const letters = list(26, '').map((_, index) => String.fromCharCode(97 + index))
// ['a', 'b', 'c', ..., 'z']

注意事项

  1. 浅拷贝: 如果传入对象或数组,所有元素都会引用同一个对象
  2. 长度限制: 长度必须是非负整数
  3. 性能: 时间复杂度为 O(n),其中 n 是数组长度
  4. 内存: 会创建指定长度的数组,注意内存使用

与其他方法的区别

  • Array(n).fill(value): 原生方法,功能相同
  • list(): radash提供的更简洁的API
  • Array.from({length: n}, () => value): 更灵活但更复杂

实际应用场景

  1. 初始化数组: 创建固定长度的数组用于后续操作
  2. 占位符: 为表单、列表等创建占位符元素
  3. 测试数据: 创建测试用的重复数据
  4. 缓冲区: 创建固定大小的缓冲区
  5. 矩阵初始化: 初始化二维数组的行或列

Released under the MIT License.