【问题标题】:I am getting an error that message is not defined我收到消息未定义的错误
【发布时间】:2022-11-19 20:37:44
【问题描述】:
function consoleStyler(color, background, fontSize, txt) 
{ 
    var message = "%c" + txt;
    var style = `color: ${color}`; 
    style = `background:${background}`;
    style = `fontSize:${fontSize}`;
    console.log(style) 
} 


function celebrateStyler(reason)
 {
    var fontStyle = "color: tomato; font-size: 50px"; 
    if (reason == "birthday")  {  
        console.log('%cHappy Birthday', fontStyle) 
    }
    else if (reason == 'champions') {
        console.log('%cCongrats on the title!', fontstyle)
    }
    else { 
        console.log(message, style)
    }
 }

 consoleStyler('#1d5c63', '#ede6db', '40px', 'congrats!');
 celebrateStyler('birthday') 


function styleAndCelebrate() 
{
     consoleStyler(color, background, fontSize, txt);
     celebrateStyler(reason);
} 
styleAndCelebrate('#ef7c8e', '#fae8e0', '30px', 'You made it!', 'champions')

我收到消息未定义的错误。现在我知道 var 是函数作用域的,所以它不能在函数外使用。但 Coursera 上的作业坚持认为

【问题讨论】:

    标签: javascript


    【解决方案1】:

    是的,您不能在其定义的范围之外使用变量。
    但是,我在尝试运行您的代码时遇到的第一个错误是 colorstyleAndCelebrate 函数中未定义。

    您没有为 styleAndCelebrate 定义参数,因此这两个参数都没有传递到最后一行的函数中:

    styleAndCelebrate('#ef7c8e', '#fae8e0', '30px', 'You made it!', 'champions')
    

    要解决此问题,请为 styleAndCelebrate 定义所需的参数:
    function styleAndCelebrate(color, background, fontSize, txt, reason)

    celebrateStyler 你会遇到同样的问题

    【讨论】:

    • 此外,在第一个函数中,您将重新分配样式 2 次。您将看到登录到控制台的唯一内容是字体大小。此外,您似乎仍在作为初学者学习 javascript,因此请扔掉 var 并开始使用 let 和 const 作为变量。他们好多了。
    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 2020-01-17
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 2018-01-05
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多