我是靠谱客的博主 从容小蝴蝶,最近开发中收集的这篇文章主要介绍JavaScript 学习-12.模板字符串(Template Strings)前言模板字符串(Template Strings)引用变量插入表达式调用函数,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

前言

JavaScript 在ES6 新增了模板字符串(Template Strings)语法,其作用是可以在字符串中换行,以及将变量和表达式插入字符串。
Internet Explorer 不支持模板字面量。

模板字符串(Template Strings)

模板字面量使用反引号 (``) 而不是单引号 (‘’) 或双引号 (“”) 来定义字符串

let a = `这个是一个模板字符串`;
console.log(a);

let b = `Hello World!`;
console.log(b);

可以在模板字符串中同时使用单引号和双引号

let c = `hello "world", hei 'yoyo'`;

也可以使用空格和换行定义多行文本

let c = `<div>
    <h1>hello world!</h1>
</div>`;
console.log(c);

引用变量

可以在字符串中引用一个变量的值,也就是相当于python的字符串格式化, 使用语法

${变量名}

简单示例

let user = "yoyo";
let x = `my name is ${user}`
console.log(x);  // my name is yoyo

可以引用一个字符串变量,也可以引用数字变量

let user = "yoyo";
let age = 20;
let x = `my name is ${user}, age is ${age}`
console.log(x);  // my name is yoyo, age is 20

插入表达式

模板字符串中也可以插入一个表达式

let user = "yoyo";
let age = 20;
let x = `my name is ${user}, age is ${age+5}`
console.log(x);  // my name is yoyo, age is 25

插入表达式示例

let x = 10;
let y = 5;
aa = `x - y 的值: ${x-y}`
console.log(aa);  // x - y 的值: 5

调用函数

在模板字符串中可以调用函数

function  fun1() {
    return "hello world"
}
let x = `fun1 return: ${fun1()}`;
console.log(x);   // fun1 return: hello world

也可以调用函数表达式

const fun2 = function () {
    return "hello world"
};
let y = `fun1 return: ${fun2()}`;
console.log(y);   // fun1 return: hello world

备注:Internet Explorer 不支持模板字面量。

最后

以上就是从容小蝴蝶为你收集整理的JavaScript 学习-12.模板字符串(Template Strings)前言模板字符串(Template Strings)引用变量插入表达式调用函数的全部内容,希望文章能够帮你解决JavaScript 学习-12.模板字符串(Template Strings)前言模板字符串(Template Strings)引用变量插入表达式调用函数所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部