(译文)学习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 ...
随机推荐
- Linux显示2015年日历表
Linux显示2015年日历表 youhaidong@youhaidong-ThinkPad-Edge-E545:~$ cal 2015 2015 一月 二月 三月 日 一 二 三 四 五 六 日 一 ...
- iOS - MySQL 的安装配置
前言 提前下载好相关软件,且安装目录最好安装在全英文路径下.如果路径有中文名,那么可能会出现一些莫名其妙的问题. 提前准备好的软件: mysql-5.7.17-macos10.12-x86_64.dm ...
- 你该怎么选Offer
原文出处:http://www.360doc.com/content/15/1223/07/1209677_522436084.shtml 记录目的:自勉.分享 摘要 一段时间无数公司.无数投资人蜂拥 ...
- I2C总线协议的软件模拟实现方法
I2C总线协议的软件模拟实现方法 在上一篇博客中已经讲过I2C总线通信协议,本文讲述I2C总线协议的软件模拟实现方法. 1. 简述 所谓的I2C总线协议的软件模拟实现方法,就是用软件控制GPIO的输入 ...
- WPF自学入门(四)WPF路由事件之自定义路由事件
在上一遍博文中写到了内置路由事件,其实除了内置的路由事件,我们也可以进行自定义路由事件.接下来我们一起来看一下WPF中的自定义路由事件怎么进行创建吧. 创建自定义路由事件分为3个步骤: 1.声明并注册 ...
- Flex 关于 keyDown事件的添加和移除(另附添加事件的执行带参数的函数)
今天遇到一个棘手的问题,原本的textInput控件有一个keyDown事件,但是不是所有的用户都需要,麻烦了首先先删除控件里面的keyDown,这个事件放在这谁都得用,我就是不想用这就实现不了,怎么 ...
- 由html,body{height:100%}引发的对html和body的思考
html,body{height:100%} 今天看到一个CSS样式:html,body{height:100%},第一次看到,感觉挺奇怪,为什么html还需要设置height:100%呢,html不 ...
- JavaScript:['1','2','3'].map(parseInt)问题解析
最近碰到了['1','2','3'].map(parseInt)这种看似不起眼陷阱却极大的问题. 这乍一看,感觉应该会输出[1,2,3].但是,实际上并不是我们想的这样.你可以现在打开console, ...
- 命令行更新node和npm
Windows系统下: 查看版本的命令和Ubuntu下一样. 不同的是Windows下不能使用"n"包管理器来对NodeJS进行管理,在这里我们使用一种叫"gnvm&qu ...
- C#多线程之异步编程
c#中异步编程,主要有两种方法: 1.委托的异步调用: 2.Task的await,async (c# 4.5) 我们来看例子: /// <summary> /// 异步保存网页,url:网 ...