简体   繁体   中英

How to use template literals for concatenation in Javascript?

I am trying to use template literals in code but it's not working.

let myData =
        (myNewData[0].checked ? Enum.ONE.concat(',') : '') +
        (myNewData[1].checked ? Enum.TWO.concat(',') : '') +
        (myNewData[2].checked ? Enum.THREE : '');
    myData = myData.replace(/,\s*$/, '');

I want to check if first or second or third is checked then I should get result with comma separated like - One,Two,Three .

It is all working fine. But I am optimizing the code & want to remove concat with Template Literals, How can I do it ?

I tried this also -

let myData = (myNewData[0].checked ? `$(Enum.ONE) , $(myNewData[1].checked) ? `Enum.TWO , `(myNewData[2].checked ? Enum.THREE)
    myData = myData.replace(/,\s*$/, "");

How can I optimize this code as I am getting the error while using template literals (back tick). I am new in using template literals, Can anyone help me in this ?

Since each item in the Enum is tied to an element in the myNewData array, consider changing it to be an array of strings instead of an object of strings. Then you can filter the array by whether the myNewData at the same index is checked, then join by commas:

const TEXTS = ['One', 'Two', 'Three'];
const output = TEXTS
  .filter((_, i) => myNewData[i].checked)
  .join(',');

您应该在模板文字中使用大括号 ${ } 而不是括号 $( )

I think this is the way to use template literals for concatenation in Javascript.

const a = `${myNewData[0].checked ? Enum.ONE: ''}${myNewData[1].checked ? `, ${Enum.TWO}`: ''}${myNewData[2].checked ? `, ${Enum.THREE}`: ''}`

On the other hand, there is more "clean" ways to do that...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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