21.模板字符串和标签模板字符串

2022-02-10  本文已影响0人  静昕妈妈芦培培

ES6新增了模板字符串,用于字符串拼接

const name = "why";
const age = 18;
const height = 1.88;

const info = `my name is ${name},age is ${age},height is ${height}.`; //变量
const info1 = `age double is ${age * 2}`; //表达式

function getDoubleAge() {
  return age * 2;
}
const info2 = `double age is ${getDoubleAge()}`; //函数调用
console.log(info)
console.log(info1)
console.log(info2)
image.png

ES6新增了标签字符串

const name = "why";
const age = 18;
const height = 1.88;
function foo(arr, arg1, arg2, arg3) {
  console.log(arr, arg1, arg2, arg3);
}
foo``; 
//[ '' ] undefined undefined undefined
foo`my name is ${name},age is ${age},height is ${height}`; 
//[ 'my name is ', ',age is ', ',height is ', '' ] why 18 1.88
foo`my name is ${name},double age is ${age * 2},height is ${height}`; 
//[ 'my name is ', ',double age is ', ',height is ', '' ] why 36 1.88

标签模板字符串执行结果:

非常感谢王红元老师的深入JavaScript高级语法让我学习到很多 JavaScript 的知识

上一篇 下一篇

猜你喜欢

热点阅读