2017-08-14 13 views
0

私は使用条件文

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

..彼らは含まれる変数に文字列を定義するために、よりエレガントな方法を知っている が、私は、私はどうなる前ES6の条件を追加する場合テンプレートリテラルを作成します。

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

この条件を実装するためのよりエレガントな方法がありますか?ショートカットを含めることは可能ですか?

+2

は、私はあなたが 'VAR書かれていなかった理由を不思議に思うもう一つの例。 if(条件付き)a = "text" + a + "more text"; else = "text" + b + "more text"; 'before。もちろん、ES6では三項演算子を使用することができます! – Bergi

答えて

6

使用この:

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

あなたは&&

let result = `${true && `content`}` 

を使用することができ、拡張の例は次のようになります。

let heading = true; 
let markup = `${heading && `<h1>Title</h1>`}`; 

let title = "My Title"; 
let mySubHeading = ""; // using false will print "false" use '' instead. 
let markup = ` 
<header> 
    ${title && `<h1>`+title+`</h1>`} 
    ${mySubHeading && `<h2>`+mySubHeading+`</h2>`} 
</header> 
` 

console.log(markup); 

// <header> 
// <h1>My Title</h1> 
// 
// </header>