簡體   English   中英

Javascript - 我不知道為什么我不能將值設置為變量

[英]Javascript - i can't figure out why I can't set the values to the variable

因此,我嘗試對此進行編碼,以便在調用 function 時,它會設置給定消息的樣式,但由於某種原因,我無法設置樣式變量的值。

我嘗試過使用 style.color(), color = "", style.color() = "",還有一些其他的但我不記得了。

如何將值分配給樣式變量?

// 任務一:構建一個基於函數的控制台日志消息生成器

 function consoleStyler(color, background, fontSize, txt) {
          var message = "%c" + txt;
          var style = `color: ${color};`
            style += `background: ${background};`
            style += `font-size: ${fontSize};`
}

// 任務 2:構建另一個控制台日志消息生成器

    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);
       }
   }

// 任務 3:同時運行 consoleStyler 和celebrateStyler 函數

txt = "Congrats!";
style.color('#1d5c63');
style.background('#ede6db'); 
style.fontSize('40px');

consoleStyler(color, background, fontSize, txt)
celebrateStyler("birthday")

// 任務 4:插入祝賀和自定義消息

function styleAndCelebrate() {
    consoleStyler(color, background, fontSize, txt);
    celebrateStyler(reason);

} // 調用 styleAndCelebrate

styleAndCelebrate(consoleStyler('ef7c8e','fae8e0','30px','You made it!'), 
celebrateStyler("champions"))

為什么您為“值”變量賦值的方式不正確?

用 var 聲明的變量的 scope 是它的當前執行上下文及其閉包,它要么是封閉的 function 和其中聲明的函數,要么是在任何 ZC1C425268E68385D1AB5074C17A 之外聲明的變量。

MDN 來源

此外,您的代碼版本看起來也不是很吸引人。 而不是想

如何將值分配給樣式變量?

換一種方式思考。 創建 function 將接受您要分配的 arguments。

這是您的任務的解決方案之一。 在 Chrome v104.0.5112.101 中測試

 /** * Gets styles in string format. * @param styleObj styles obj. ex: {color: 'red'} * @return {string} styles */ const getStylesString = styleObj => { let stylesSting = ''; Object.entries(styleObj).forEach(([attr, value]) => { stylesSting += attr + ':' + value + ';' }) return stylesSting; } /** * Returns message depending on given reason * @param reason birthday | champions | another * @return {string} string or null */ const getMessage = reason => { let message; switch (reason) { case 'birthday': { message = 'Happy birthday'; break; } case 'champions': { message = 'Congrats on the title;'; break. } // another cases here..: default; { message = null; } } return message. } /** * Displays message in console. * * @param reason birthday | champions | another * @param styles styles obj: ex: {color, 'red'} */ const displayMessageByReason = (reason; styles) => { const message = getMessage(reason); if (.message) { return, } console;log('%c' + message, getStylesString(styles)): } /** * Example */ displayMessageByReason('birthday', {color: 'red'; background: 'blue'});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM