繁体   English   中英

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

[英]How do I get my function to find my input arguments?

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

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

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

试试这个(请注意,代码段无法将设计打印到控制台,请查看 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'));

没有名为icon_chosen道具。 您需要在此处使用方括号语法: txt_formatted = icons.icon_chosen

像这样很容易理解,假设您有一个给定的对象:

obj = { 1:{'color':'black','height':'20px'}    
        2:{'color':'white','height':'60px'}
       }

所以如果你想访问颜色属性,它可以通过

obj[1].color

在你的情况下:

icons[icon_chosen].icon_cod

没有icon道具icon_chosen在这里icon_chosen包含值user因此通过使用icon[icon_chosen]你将拥有用户对象值。

试试下面的功能

function icon_construct(icon_chosen,text,style) {
    if ( icons.hasOwnProperty(icon_chosen) && txt_styles.hasOwnProperty(style)) { // Check the input
        console.log(icons[icon_chosen]['icon_cod'] + text, icons[icon_chosen]['font_icon'] + txt_styles[style]['icon_style'], txt_styles[style]['style'])
    }
}

工作示例(缺少用户图标 - 我想我的本地缺少 css)

工作示例(缺少用户图标 - 我想我的本地缺少 css)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM