syntactic suguar 语法糖
Default parameters
Template strings
use backtick symbol
backtick 反引号
bracket 大括号
var displayName = `Todo #${todo.id}`;
tsc app.ts
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"declaration": true,
"module": "system",
"sourceMap": true,
"experimentalDecorators": true
}
}
tsc --watch
nonetheless尽管如此
Let and const
at our disposal 任由我们处置
For…of loop
a concise way to 一种简明的方式
clunky沉重的
iterate over an array 遍历/迭代数组
var array = ["pick up ", "wash", "eat", "sleep"];
for (let index = 0; index < array.length; index++) {
const element = array[index];
console.log(element);
}
for (const key in array) {
if (Object.prototype.hasOwnProperty.call(array, key)) {
const element = array[key];
console.log(element);// For-In Loop,需要遍历下标index
}
}
for (const iterator of array) {
console.log(iterator); // For-Of Loop,语法糖,不需要index
}
Lambdas
wacky behaviours 古怪的行为 than “this” keyword
function Counter(el) {
this.count = 0;
el.innerHTML = this.count;
console.log(this.count);//0
el.addEventListener("click", function () {
this.count += 1;
//此处this变成了<div id="container">0</div>
console.log(this);//refers to the gloal browser scope
el.innerHTML(this.count);
});
// solution:解决办法是先在外面把这个值存一下
let _this = this;
el.addEventListener("click", function () {
_this.count += 1;
el.innerHTML = _this.count;
});
}
new Counter(container);
ES2015 introduced a new feature called arrow function箭头函数解决此类this问题,in C# they are called Lambda expressions.
In those languages, they’re called Lambda expressions. You can convert pretty much any JavaScript function into an arrow function, by simply removing the function keyword from the front, and then inserting equals greater than or arrow, hence the name of the feature after the parameter list. And that’s it.
el.addEventListener("click", ()=> {
this.count += 1;
el.innerHTML = this.count;
});
when the arrow function only accepts one parameter, I can even omit the parentheses around the parameter name.
var filtered = [1, 2, 3].filter(x => x > 2);
console.log(filtered);//[3]
Destructuring 解构
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
In this chapter, I’ve been demonstrating all of the language features that are new in ECMAScript 2015. The features I’ve shown so far, features such as arrow functions and string templates, are the ones that I use on a regular basis in just about any TypeScript file that I work in. The last few features I’m about to show, however, I tend to use a whole lot less少用, if at all如果某事真会发生的话, and I expect that you’ll have the same limited need for them as I do.我希望你会和我一样对它们有有限的需求
Destructuring解构 which is the ability to assign values to multiple variables from a single object with a single statement.一个对象给多个变量赋值
et cetera 等等诸如此类
flip the values把值对换/交换
but that doesn’t have to be the case. 但事实并非如此。
//数组
var arrary = [123, "pick up sth", false];
var [id, title, completed] = arrary;
var a = 1;
var b = 5;
//不能直接写a=b
[a, b] = [b, a];
//对象
var todo = {
id: 1,
name: "eat",
isCompleted: true,
};
var { id, name, isCompleted } = todo;
console.log(id);
//函数取值
function getTodo(id) {
var todo = {
id: 123,
title: "eat",
completed: false,
};
return todo;
}
var { id, title, completed: isComplete } = getTodo(123);
//第三个属性可以把completed赋值给isCompleted
design pattern设计模式
All of this is nice, but perhaps the most effective use of destructuring is to reduce a long list of method parameters down into a single option object that contains all of those parameters as properties instead.
所有这些都很好,但也许对解构最有效的使用是,将一长串方法参数,缩减到一个 包含所有这些参数作为属性的选项对象(如下面的options,就是object parameter)。
function countdown(options) {
//繁琐
var options = options === undefined ? {} : options,
initial = options.initial === undefined ? 10 : options.initial,
final = options.final === undefined ? 0 : options.final,
interval = options.interval === undefined ? 1 : options.interval;
var current = initial;
while (current > final) {
console.log(current);
current -= interval;
}
}
countdown({ initial: 5, final: 0, interval: 1 });
简化后
function countdown({
initial,
final: final = 0,
interval: interval = 1,
initial: current,
}) {
while (current > final) {
console.log(current);
current -= interval;
}
}
countdown({ initial: 5 });
The spread operator 展开操作符…
先说splice用法Array.splice() 方法添加数组元素:
Array.prototype.splice()
array.splice(index, howmany, item1, …, itemX)
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// 在位置 2,添加 2 个元素:
fruits.splice(2, 0, "Lemon", "Kiwi");
//Banana,Orange,Lemon,Kiwi,Apple,Mango
function add() {
var values = Array.prototype.splice.call(arguments, [0]),
total = 0;
for (var value of values) {
total += value;
}
return total;
}
add(1, 2, 3);//6
//用展开语法,represented by three periods ... in front of it
function add(...values) {
var total = 0;
for (var value of values) {
total += value;
}
return total;
}
add(1, 2, 3); //6
//但它必须作为最后一个参数
function calc(action, ...values) {
var result = 0;
switch (action) {
case "add":
for (const value of values) {
result += value;
}
break;
case "subtract":
for (const value of values) {
result -= value;
}
break;
default:
break;
}
return result;
}
calc('add',1,2,3);
var a = [3, 4, 5];
var b = [1, 2, ...a, 6, 7];
//[1,2,3,4,5,6,7]
populate
v.(大批人或动物)居住于,生活于;充满,出现于(某地方,领域);迁移,殖民于;(给文件)增添数据,输入数据
var a = [1, 2, 3];
var b = [4, 5, 6, 7];
Array.prototype.push.apply(a, b);
// a: [1,2,3,4,5,6,7] b: [4, 5, 6, 7];
//展开语法
a.push(...b);
Computed properties
存储型属性(stored property)
计算型属性(computed property)
come in quite handy 派上用场,很有用
let’s say 比如说
var support = {
os_Windows: isSupported("Windows"),
os_iOS: isSupported("iOS"),
os_Android: isSupported("Android"),
};
function isSupported(os) {
return Math.random() >= 0.5; //返回true/faluse,只是为了表示返回结果是不确定的
}
The first thing we need to do to convert the property names into computed properties is first wrapping them in brackets
将属性名变成计算型属性,先用中括号[ ] 括起来
用表达式加上前缀
const osPrefix = "os_";
var support = {
[osPrefix + "Windows"]: isSupported("Windows"),
[osPrefix + "iOS"]: isSupported("iOS"),
[osPrefix + "Android"]: isSupported("Android"),
};
function isSupported(os) {
return Math.random() >= 0.5; //只是为了表示返回结果是不确定的
}
// 执行supprot后得到
{
"os_Windows": true,
"os_iOS": false,
"os_Android": true
}