(译文)学习ES6非常棒的特性-字符串常量基础
字符串常量基础
在ES2015之前我们是这么拼接字符串的:
var result = 10;
var prefix = "the first double digit number I learnt was ";
var assembled = prefix + result.toString();
console.log(assembled); // logs => 'the first double digit number I learnt was 10'
在ES2015我们可以这么做:
var result = 10;
var assembled = `the first double digit number I learnt was ${result}`;
console.log(assembled); // logs => 'the first double digit number I learnt was 10'
通过 ${}引用外部的变量
字符串常量拼接里面遍历
假设我们有一个数组,我们怎么遍历它:
var data = [
// Data here
];
// loop through the data
data.forEach((datarecord, idx) => {
// for each record we call out to a function to create the template
let markup = createSeries(datarecord, idx);
// We make a div to contain the resultant string
let container = document.createElement("div");
container.classList.add("as-Series");
// We make the contents of the container be the result of the function
container.innerHTML = markup;
// Append the created markup to the DOM
document.body.appendChild(container);
});
function createSeries(datarecord, idx) {
return `
<div class="a-Series_Title">${datarecord.Title}</div>
`;
}
完整的拼接方法类似这样:
function createSeries(datarecord, idx) {
return `
<h2 class="a-Series_Title">${datarecord.Title}</h2>
<p class="a-Series_Description">
<span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description}
</p>
<div class="a-EpisodeBlock">
<h4 class="a-EpisodeBlock_Title">First episodes</h4>
</div>
`;
}
如果数据里面又有一个数组,怎么遍历?
function createSeries(datarecord, idx) {
return `
<h2 class="a-Series_Title">${datarecord.Title}</h2>
<p class="a-Series_Description">
<span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description}
</p>
<div class="a-EpisodeBlock">
<h4 class="a-EpisodeBlock_Title">First episodes</h4>
${datarecord.Episodes.map((episode, index) =>
`<div class="a-EpisodeBlock_Episode">
<b class="">${index+1}</b>
<span class="">${episode}</span>
</div>
`
)}
</div>
`};
ok. 然后打印出来:
Episodes
1 Homecoming
,
2 New Colossus
,
3 Champion
,
4 Away
,
5 Paradise
,
6 Forking Paths
,
7 Empire of Light
,
8 Invisible Self
多了一个默认的逗号,怎么办。
${datarecord.Episodes.map((episode, index) =>
`<div class="a-EpisodeBlock_Episode">
<b class="">${index+1}</b>
<span class="">${episode}</span>
</div>
`
).join("")}
通过join方法处理一下就好了。
字符串常量里面用if/else
${datarecord.Ended === true ? `` : `<div class="a-Series_More">More to come!</div>`}
使用返回另外一个值的函数
假设我们有这样一个函数
const add = (a, b) => a + b;
function getRatingsAverage(ratings) {
return ratings.reduce(add) / ratings.length;
}
这样使用就可以了:
`<div class="a-UserRating">Average user rating: <b class="a-UserRating_Score">${getRatingsAverage(datarecord.UserRatings)}</b></div>`
安全
看一个例子:
var username = 'craig<script>alert("XSS")</' + 'script>';
document.write(`<p>Hi ${username}</p>`);
用户输入了一个js代码,然后我们直接填充到了username里面。这个时候会导致浏览器弹出一个alert。 这样肯定是不行的。
一般我们需要escape方法转义一下,或者用textContent。
// HTML Escape helper utility
var util = (function () {
// Thanks to Andrea Giammarchi
var
reEscape = /[&<>'"]/g,
reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,
oEscape = {
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
},
oUnescape = {
'&': '&',
'&': '&',
'<': '<',
'<': '<',
'>': '>',
'>': '>',
''': "'",
''': "'",
'"': '"',
'"': '"'
},
fnEscape = function (m) {
return oEscape[m];
},
fnUnescape = function (m) {
return oUnescape[m];
},
replace = String.prototype.replace
;
return (Object.freeze || Object)({
escape: function escape(s) {
return replace.call(s, reEscape, fnEscape);
},
unescape: function unescape(s) {
return replace.call(s, reUnescape, fnUnescape);
}
});
}());
// Tagged template function
function html(pieces) {
var result = pieces[0];
var substitutions = [].slice.call(arguments, 1);
for (var i = 0; i < substitutions.length; ++i) {
result += util.escape(substitutions[i]) + pieces[i + 1];
}
return result;
}
var username = "Domenic Denicola";
var tag = "& is a fun tag";
console.log(html`<b>${username} says</b>: "${tag}"`);
以上就是今天的内容,感谢阅读。
更多内容,点击阅读原文:
https://benfrain.com/html-templating-with-vanilla-javascript-es2015-template-literals/
作者知乎/公众号:前端疯
(译文)学习ES6非常棒的特性-字符串常量基础的更多相关文章
- (译文)学习ES6非常棒的特性——Async / Await函数
try/catch 在使用Async/Await前,我们可能这样写: const main = (paramsA, paramsB, paramsC, done) => { funcA(para ...
- (译文)学习ES6非常棒的特性-深入研究var, let and const
Var var firstVar; //firstVar被声明,它的默认值是undefined var secondVar = 2; //secondVar被声明,被赋值2 先看一个例子: var i ...
- ES6非常棒的特性-解构
https://blog.csdn.net/maoxunxing/article/details/79772946
- 用简单的方法学习ES6
ES6 简要概览 这里是ES6 简要概览.本文大量参考了ES6特性代码仓库,请允许我感谢其作者@Luke Hoban的卓越贡献,也感谢@Axel Rauschmayer所作的[优秀书籍]//explo ...
- ES6的一些常用特性
由于公司的前端业务全部基于ES6开发,于是给自己开个小灶补补ES6的一些常用特性.原来打算花两天学习ES6的,结果花了3天才勉强过了一遍阮老师的ES6标准入门(水好深,ES6没学好ES7又来了...) ...
- Spring Boot 揭秘与实战(四) 配置文件篇 - 有哪些很棒的特性
文章目录 1. 使用属性文件2. YAML文件 1.1. 自定义属性 1.2. 参数引用 1.3. 随机数属性 1.4. application-{profile}.properties参数加载 3. ...
- ES6中的新特性
本人最近学习es6一些方法,难免有些手痒,想着能不能将这些方法总结下,如下 1.数组的扩展 1)首先什么是伪数组 无法直接调用数组方法或期望length属性有什么特殊的行为,但仍可以对真正数组遍历方法 ...
- ES6的十个新特性
这里只讲 ES6比较突出的特性,因为只能挑出十个,所以其他特性请参考官方文档: /** * Created by zhangsong on 16/5/20. */// ***********Nu ...
- 深入浅出:了解JavaScript的ES6、ES7新特性
参照阮一峰博客:http://es6.ruanyifeng.com/#README es6常见题:https://blog.csdn.net/qq_39207948/article/details/8 ...
随机推荐
- hibernate(二)主键生成策略
hibernate主键生成策略主要指的是在实体类orm的配置 <id name=""> <generator class="native"&g ...
- Luogu4137:Rmq Problem/mex
题面 传送门 Sol 这题可能是假的 离线莫队搞一搞,把数字再分块搞一搞,就行了 # include <bits/stdc++.h> # define IL inline # define ...
- c++ STL容器适配器
一.标准库顺序容器适配器的种类 标准库提供了三种顺序容器适配器:queue(FIFO队列).priority_queue(优先级队列).stack(栈) 二.什么是容器适配器 &q ...
- 论文笔记(8):BING: Binarized Normed Gradients for Objectness Estimation at 300fps
译文: <基于二值化赋范梯度特征的一般对象估计> 摘要: 通过训练通用的对象估计方法来产生一组候选对象窗口,能够加速传统的滑动窗口对象检测方法.我们观察到一般对象都会有定义完好的封闭轮廓, ...
- JVM堆外内存随笔
一 JVM堆外内存 1)java与io(file,socket)的操作都需要堆外内存与jvm内存进行互相拷贝,因为操作系统是不懂jvm的内存结构的(jvm的内存结构是自管理的),所以堆外内存存放的是操 ...
- Problem : (1.2.1) Text Reverse
#include<iostream> using namespace std; void main() { char arr[1000]; int a,n; int s,t; cin> ...
- 纯代码实现WordPress评论回复自动添加@评论者的功能
先看看效果: 这个有什么用呢?添加了@功能之后那些用户评论之间的层次关系就很清晰了,我们可以清楚地知道这些评论是谁发给谁的. 其实主要是为了提升逼格. 实现方法: 将下面代码加入function.ph ...
- Firefox取消“订阅实时书签”功能
如果你勾选了Firefox“总是用实时书签订阅收取”, 一打开RSS页面就直接弹出添订阅实时书签对话,而当你想在火狐中直接查看RSS页面时,发现不知如何取消“订阅实时书签”功能了.就怨这个关闭功能藏的 ...
- 【Unity3D与23种设计模式】组合模式(Composite)
前段时间在忙一个新项目 博客好久没有更新了 GoF中定义: "将对象以树状结构组合,用以表现部分-全体的层次关系.组合模式让客户端在操作各个对象或组合时是一致的." 是一致的意思就 ...
- CucumberJS 资源
https://cucumber.io/docs/reference/javascript https://github.com/cucumber/cucumber-js