进入while循环后变量丢失

Variable lost after entering a while loop

代码:

    /**
     * Converts all numbers in text from old unit to new unit
     *
     * @param {string} Text Text that will be converted
     * @param {string} UnitName Name of current unit
     * @param {string} NewUnitName Name of the new unit
     * @param {function} UnitConvertFunc Function that takes current unit float and returns new unit float
     * @return {string} Text with all old unit floats replaced by new unit floats
     */
function ReplaceUnit(Text,UnitName,NewUnitName,UnitConvertFunc) {
        let NewText = "";
        let lastUnitTextIndex = -UnitName.length;

        let unitTextIndex = Text.toLowerCase().indexOf(UnitName);
        let unitTextFragment = Text.slice(lastUnitTextIndex+UnitName.length, unitTextIndex)
        lastUnitTextIndex = unitTextIndex;

        console.log(unitTextFragment) //ok
        while (unitTextIndex!=-1) {
            console.log(unitTextFragment) //ERROR: variable is not initialized!!!
            let i = 0;

            LfragmentLoop:
            while (i < unitTextFragment.length)
            { 
                let firstDigitPos;
                let lastDigitPos;
                for (i; ;i++) { //Searches for first digit symbol
                    if (i == unitTextFragment.length) { 
                        console.log(`${DebugText}no Number found before \"${UnitName}\" text: ${unitTextFragment}`);
                        break LfragmentLoop;
                    }
                    if (isFloatNumber(unitTextFragment[i])) break;  
                }

                firstDigitPos = i;

                for (i+=1;i < unitTextFragment.length; i++) {
                    if (isFloatNumber(unitTextFragment[i])) lastDigitPos = i;
                    else break;
                }

                let UnitNumber = unitTextFragment.slice(firstDigitPos,lastDigitPos+1);

                unitTextFragment = unitTextFragment.slice(0,firstDigitPos) + UnitConvertFunc(UnitNumber) + unitTextFragment.slice(lastDigitPos+1);

                i++;


            }

            NewText+=unitTextFragment + NewUnitName;
            let unitTextIndex = Text.toLowerCase().indexOf(UnitName, NewText.length+UnitName.length);
            if (unitTextIndex==-1) break;
            let unitTextFragment = Text.slice(lastUnitTextIndex+UnitName.length, unitTextIndex)
            lastUnitTextIndex = unitTextIndex;
        }
    }

我很震惊,为什么会这样?

看来我的post主要是代码,但我不知道我还能添加更多细节。对我旨在解决问题的行动的描述是无用的,因为多亏了他们,我发现了一个特定的错误点,我无法想象在 while 循环开头的一行中可以写错什么。我试着在引号中包含'-1',它没有改变任何东西

你在外循环中有这一行,接近结尾:

let unitTextFragment = Text.slice(lastUnitTextIndex+UnitName.length, unitTextIndex)
        

这意味着你定义了一个new变量,具有块范围:它的范围是while循环的主体。由于提升规则,它不会在该循环的第一次迭代中定义(查找:)。

解决方法:移除let.