相同的函数在javascript中编写方式不同

相同的函数在javascript中编写方式不同,javascript,electron,Javascript,Electron,各位。我正在用electron编写一个应用程序,运行一个函数很困难 为什么这样做有效: function ReplaceText () { const replaceText = (selector, text) => { const element = document.getElementById (selector); if (element) element.innerText = text

各位。我正在用electron编写一个应用程序,运行一个函数很困难

为什么这样做有效:

function ReplaceText ()
{
    const replaceText = (selector, text) => 
    {
        const element = document.getElementById (selector);
        
        if (element)
            element.innerText = text;
    }

    for (const type of ['chrome', 'node', 'electron']) 
    {
        replaceText 
        (
            `${type}-version`, 
            process.versions [type]
        );
    }
}
但这并不是:

var ReplaceText = function ()
{
    for (const type of ['chrome', 'node', 'electron']) 
    {
        if (document.getElementById (process.versions [type]))
        {
            element.innerText = `${type}-version`;
        }
    }
}

看起来您在非工作代码中如何使用它们时混淆了
选择器、文本的顺序。另外,您没有在任何地方声明
元素
,而是在
if
块中使用它

请尝试以下方法:

var ReplaceText = function ()
{
    for (const type of ['chrome', 'node', 'electron']) 
    {
        const element = document.getElementById(`${type}-version`);
        if (element)
        {
            element.innerText = process.versions[type];
        }
    }
}

当您调用
document.getElementById(选择器)
时,在第一个函数中,您给它
${type}-version
,但在第二个函数中,您给它
process.versions[type]
。也许这就是问题所在?你还没有定义
元素
什么是
元素
?@charlietfl很好,甚至没有看他的代码的其余部分,现在就可以解决了。