首页 > 解决方案 > 如何让我的函数找到我的输入参数?

问题描述

我正在创建一个函数,该函数将使用预定义的样式格式化我的输入文本。

const icons = {
    user: {'icon_cod': '%c  %c', 'font_icon': 'font-family:"Font Awesome 5 Free"; font-weight: 900;'} // declare my icon
}
const txt_styles = {
    texto: {'style': 'color:red; font-family: "Open Sans"; font-weight: 700; font-size: 15px;', // Format my text and icon
            'icon_style': 'color:blue;'}
}

function icon_construct(icon_chosen,text,style) {
    txt_formatted = '' 
    if (icon_chosen in icons && style in txt_styles) { // Check the input 
        txt_formatted = icons.icon_chosen['icon_cod'] + text, icons.icon_chosen['font_icon'] + txt_styles.style['icon_style'], txt_styles.style['style']
    } return txt_formatted // Returns formatted text
}

console.log(icon_construct('user','Hello World','body')); 

但是退出是向我返回此错误:

返回错误

预期的输出将是这个

在此处输入图像描述

举例说明格式化是如何发生的

    //Run in the browser console
    console.log ('%c Red %c Blue','color: red; ','color: blue; ')

样式遵循元素声明的顺序 函数未找到参数的值

标签: javascript

解决方案


试试这个(请注意,代码片段无法将设计打印到控制台,请查看 devtools 以查看结果):

const
    icons = {
        user: {
            iconCode: '%c  %c',
            fontIcon: 'font-family: "Font Awesome 5 Free"; font-weight: 900;'
        }
    },
    textStyles = {
        text: {
            style: 'color: red; font-family: "Open Sans"; font-weight: 700; font-size: 15px;',
            iconStyle: 'color: blue;'
        }
    },
    iconConstruct = (iconChosen, text, style) =>
        iconChosen in icons && style in textStyles ? [
            icons[iconChosen].iconCode + text,
            icons[iconChosen].fontIcon + textStyles[style].iconStyle,
            textStyles[style].style
        ] : [];

console.log(...iconConstruct('user', 'Hello World', 'text'));


推荐阅读