尝试覆盖函数内的变量并收到错误:“在其声明之前使用了块范围变量 '...'.ts(2448)”

Emm*_*man 4 scope declaration function typescript

我正在编写一个打字稿函数,它接受数字数组(即type: number[])并计算其平均值。此外,我想考虑输入数组何时可能包含某些null值。为此,我添加了一个参数,当设置为 时true,告诉函数null在计算平均值之前删除 s。

但我无法找出执行此操作的正确方法,因为我无法覆盖函数内的输入。

这是我的代码calcMean()

function calcMean(arr: number[], nullRemove: boolean = true): number {
    if (nullRemove) { // if TRUE, which is the default, then throw out nulls and re-assign to `arr`
        const arr: number[] = arr.filter((elem) => elem !== null);
    }
    // then simply calculate the mean of `arr`
    return arr.reduce((acc, v, i, a) => acc + v / a.length, 0); // https://stackoverflow.com/a/62372003/6105259
}
Run Code Online (Sandbox Code Playgroud)

然后我得到一个错误:

在声明之前使用块范围变量“arr”。ts(2448)

我也尝试使用let附加或代替,const但它没有解决问题。

我在这里缺少什么?

T.J*_*der 5

两种选择供您选择:

1. 不要重新声明它,只需重新分配它:

function calcMean(arr: number[], nullRemove: boolean = true): number {
    if (nullRemove) { // if TRUE, which is the default, then throw out nulls and re-assign to `arr`
        arr = arr.filter((elem) => elem !== null);
        // ^^^ No `const` here
    }
    // then simply calculate the mean of `arr`
    return arr.reduce((acc, v, i, a) => acc + v / a.length, 0); // /sf/answers/4366040241/
}
Run Code Online (Sandbox Code Playgroud)

有些人认为重新分配参数是一种糟糕的风格(我不是其中之一,因为函数像您的情况一样很小,但我理解这个论点),所以或者:

2. 分配给不同的变量:

function calcMean(arr: number[], nullRemove: boolean = true): number {
    // Remove `null` if requested
    const a = nullRemove ? arr.filter(elem => elem !== null) : arr;
    // then simply calculate the mean of `arr`
    return a.reduce((acc, v, i, a) => acc + v / a.length, 0); // /sf/answers/4366040241/
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢您讨论参数不变性的主题。另外:使用倒置三元条件客观上会增加阅读源代码时的认知负担。 (2认同)