我在操场上有这个输出:
[1, 2, 3]
[未定义,未定义,未定义]
我只想用 5 替换第二个元素。这是我的代码:
程序.ts
import { Utils } from "./Utils";
class Program
{
public static Main(): void
{
let array = [1, 2, 3];
console.log(array);
let array2 = Utils.ArrayModify(array, 1, 5);
console.log(array2);
}
}
Program.Main();
单位.ts
export class Utils
{
public static ArrayModify<U>(array: U[], index: number, newValue: U)
{
return array.map((oldValue: U, currentIndex: number) =>
{
currentIndex === index ? newValue : oldValue;
});
}
}
array.map返回 void[] 类型,但我需要 U[]。
你忘了return
:
return currentIndex === index ? newValue : oldValue;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句