Files
2026-01-16 00:12:33 +08:00

41 lines
1.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 安全地在数组指定索引处赋值,兼容 Android 平台对稀疏数组的限制。
*
* 行为说明:
* - 非 Android等同于 arr[index] = value可能产生稀疏数组
* - Android若 index >= length则先用 undefined 填充至 index再赋值紧凑数组无空槽
*
* @param arr - 目标数组(会被修改)
* @param index - 非负整数索引
* @param value - 要设置的值
* @throws {Error} 如果 index 不是非负整数
*/
export function assignAtIndex<T>(arr : T[], index : number, value : T) : void {
// 输入校验
if (index < 0) {
throw new Error(`Index must be a non-negative integer, got ${index}`);
}
// #ifndef APP-ANDROID
// 标准环境:直接赋值(允许稀疏数组)
arr[index] = value;
// #endif
// #ifdef APP-ANDROID
// Android 环境:安全赋值,避免稀疏数组导致的异常
if (index < arr.length) {
arr[index] = value;
} else {
// 手动扩展数组,中间填充 undefined
// 注意:使用 push(undefined) 而不是 arr[length++] = undefined
// 因为某些 Android 引擎对直接 length 赋值也敏感
while (arr.length <= index) {
arr.push(null as T);
}
// arr.set(index, value)
arr[index] = value;
}
// #endif
}