【问题标题】:Using conditionals inside template literals在模板文字中使用条件
【发布时间】:2017-08-14 14:35:22
【问题描述】:

我知道有更优雅的方法来定义包含变量的字符串, 但如果我想在 pre ES6 中添加条件,我会这样做..

var a = "text"+(conditional?a:b)+" more text"

现在我会使用模板文字..

   let a;
   if(conditional) a = `test${a} more text`;
   else a = `test${b} more text`;

有没有更优雅的方式来实现这个条件?是否可以包含 if 快捷方式?

【问题讨论】:

  • 我想知道为什么你以前没有写过var a; if (conditional) a = "text"+a+" more text"; else a = "text"+b+" more text";。当然你仍然可以在 ES6 中使用三元运算符!

标签: javascript ecmascript-6


【解决方案1】:

使用这个:

let a = `test${conditional ? a : b} more text`;

【讨论】:

    【解决方案2】:

    您还可以进一步扩展它并在这样的条件中使用占位符。

    这实际上取决于您拥有的最易读的用例。

    一些例子:

    // example 1
    const title = 'title 1';
    const html1 = `${title ? `<h2>${title}</h2>` : '<h2>nothing 1</h2>'}`
    
    document.getElementById('title-container-1').innerHTML = html1;
    
    // example 2
    const title2= 'title 2';
    const html2 = `
    	${title2 ? 
      	`<h2>${title2}</h2>` : 
      	"<h2>nothing 2</h2>"
      }`
    
    document.getElementById('title-container-2').innerHTML = html2;
    
    // example 3
    const object = {
    	title: 'title 3'
    };
    
    const html3 = `
    	${(title => {
          if (title) {
            return `<h2>${title}</h2>`;
          }
    	  	return '<h2>Nothing 3</h2>';
    		})(object.title)
    	  }
    `;
    
    document.getElementById('title-container-3').innerHTML = html3;
    <div id="title-container-1"></div>
    <div id="title-container-2"></div>
    <div id="title-container-3"></div>

    (source)

    【讨论】:

      【解决方案3】:

      2021 确保虚假值:

      如果第一个条件值是数字零 0 或空字符串“”,则进一步扩展并确保条件不会中断。
      `${conditional ?? 'default value'}`
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-03
        • 1970-01-01
        • 2017-10-01
        • 1970-01-01
        • 2021-11-12
        • 2021-09-02
        • 1970-01-01
        • 2022-06-10
        相关资源
        最近更新 更多