[英]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 之外声明的变量。
此外,您的代码版本看起来也不是很吸引人。 而不是想
如何将值分配给样式变量?
换一种方式思考。 创建 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.