模板文字

    技术2022-07-11  136

    Seemingly every language has a template string enhancement, and within JavaScript we've written our own to allow more seamless development without the need to concatenate everything.  Some of these template helpers even allow for looping, iteration, and conditional support.  Native implementations always start small but I'm excited about template literals in JavaScript!

    似乎每种语言都具有模板字符串增强功能,并且在JavaScript中,我们编写了自己的模板,以实现更无缝的开发,而无需连接所有内容。 其中一些模板帮助器甚至允许循环,迭代和条件支持。 本机实现总是从小做起,但是我对JavaScript中的模板文字感到兴奋!

    JavaScript (The JavaScript)

    The template format is very simple:  backticks(`) instead of single or double quotes, and a $ for interpolation wrapping:

    模板格式非常简单:使用反引号( ` )代替单引号或双引号,并使用$进行插值包装:

    // Basic interpolation var name = 'David'; console.log(`Hi, my name is ${name}`); // Hi, my name is David // Math :) var one = 1; var two = 2; console.log(`Your total is: ${one+two}`); // Your total is: 3 // More math console.log(`Another total is: ${one + two * 2}`); // Another total is: 5 // Object properties var obj = { x: 1, y: 2 }; console.log(`Your total is: ${obj.x + obj.y}`); // Your total is: 3

    You can also use template strings for basic new line acceptance:

    您还可以使用模板字符串来接受基本的换行:

    var myString = `Hello I'm a new line`; // No error!

    The JavaScript template string feature is a nice add, and will first become available in Firefox.  This template string feature isn't groundbreaking but it's a nice enhancement and something long overdue, if only for multi-line strings.

    JavaScript模板字符串功能是一个不错的添加,它将首先在Firefox中可用。 此模板字符串功能并不是开创性的,但它是一项不错的增强功能,并且即使是仅适用于多行字符串,也早已过期。

    翻译自: https://davidwalsh.name/template-literals

    Processed: 0.012, SQL: 9