分享人:黄震
目录
1.背景介绍
2.知识剖析
3.常见问题
4.解决方案
5.编码实战
6.扩展思考
7.参考文献
8.更多讨论
ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在 2015 年 6 月正式发布了。 它的目标,是使得 JavaScript 语言可以用来编写复杂的大型应用程序,成为企业级开发语言。
下面是介绍几个ES6的新特性
var f = v => v;
f();
console.log('f()', f());
var g = function (v) {
return v;
console.log('v', v);
}
g();
console.log('g()', g());
var h = () => 5;
h();
console.log('h()', h());
var i = function () {
return 5;
}
i();
console.log('i()', i());
let [a,b,c]=[1,[2,3],[4]];
console.log(a,b,c);
const people = {
name: 'lux',
age: 20
}
const name = people.name
const age = people.age
var l = [1, 2, 3].map(function (x) {
return x * x;
})
console.log('l', l);
let n = [1, 2, 3].map(x => x * x);
console.log('n', n);
函数参数默认值
不使用ES6 为函数的参数设置默认值
function foo(height, color)
{
var height = height || 50;
var color = color || 'red';
//...
}
但是,当参数的布尔值为false时,是会出事情的!比如,我们这样调用foo函数:
foo(0, "")
因为0的布尔值为false,这样height的取值将是50。同理color的取值为‘red’。
function foo(height = 50, color = 'red')
{
// ...
}
不使用ES6
var name = 'Your name is ' + first + ' ' + last + '.'
var name = `Your name is ${first} ${last}.`
var roadPoem = 'Then took the other, as just as fair,\n\t'
+ 'And having perhaps the better claim\n\t'
+ 'Because it was grassy and wanted wear,\n\t'
+ 'Though as for that the passing there\n\t'
+ 'Had worn them really about the same,\n\t'
var roadPoem = `Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear,
Though as for that the passing there
Had worn them really about the same,`
function people(name, age) {
return {
name: name,
age: age
};
}
function people(name, age) {
return {
name,
age
};
}
Spread Operator展开运算符有什么用途?
组装对象或者数组:
//数组
const color = ['red', 'yellow']
const colorful = [...color, 'green', 'pink']
console.log(colorful) //[red, yellow, green, pink]
//对象
const alp = { fist: 'a', second: 'b'}
const alphabets = { ...alp, third: 'c' }
console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"
有时候我们想获取数组或者对象除了前几项或者除了某几项的其他项
//数组
const number = [1,2,3,4,5]
const [first, ...rest] = number
console.log(rest) //2,3,4,5
//对象
const user = {
username: 'lux',
gender: 'female',
age: 19,
address: 'peking'
}
const { username, ...rest } = user
console.log(rest) //{"address": "peking", "age": 19, "gender": "female"
es6的升序降序
// 排序
// 常规升序排序
arr = [1, 4, 5, 3, 2, 6];
var o = arr.sort(function (a, b) {
return a - b;
});
console.log('o', o, "//常规升序排序");
//es6降序
var p = arr.sort((a, b) => b - a);
console.log('p', p, "//es6降序");
对于 Object 而言,还可以用于组合成新的 Object 。 (ES2017 stage-2 proposal) 当然如果有重复的属性名,右边覆盖左边
const first = {
a: 1,
b: 2,
c: 6,
}
const second = {
c: 3,
d: 4
}
const total = { ...first, ...second }
console.log(total) // { a: 1, b: 2, c: 3, d: 4 }
感谢大家观看
制作人:高昕 | 黄震