javascript - 如何让我的函数找到我的输入参数?

标签 javascript

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

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

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

Error Returned

预期的输出是这样的

enter image description here

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

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

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

最佳答案

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

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

关于javascript - 如何让我的函数找到我的输入参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60029334/

相关文章:

javascript - "variable initializer is redundant"到底是什么意思?

javascript - 滚动时导航栏的弹跳/缓动动画

javascript - javascript 中输入字符串中带有可选元素的正则表达式

javascript - 让 html 元素保持在相同位置而不使用位置 : fixed

php - 使用此 Facebook 风格 Lightbox - 请求 AJAX - 在页面上覆盖多个按钮

Javascript语法错误不知道我做错了什么

javascript - 根据字段分割对象

javascript - 尝试将 DOMParser 与 Node js 一起使用

javascript - 禁用/隐藏第一张/最后一张幻灯片上的幻灯片箭头

javascript - 有没有可能在调用构造函数之前就知道 'this'这个对象呢?