您的位置:首页 > Web前端 > JavaScript

ES6学习资料

2017-01-16 10:06 239 查看
JavaScript ES6 核心功能一览

ES6详细文档

剩余参数(…)

从参数到剩余参数和扩展操作符。

在 ES5 中,获取任意数量的参数是非常麻烦的:

// ES5

function printf(format) {

var params = [].slice.call(arguments, 1);

console.log(‘params: ‘, params);

console.log(‘format: ‘, format);

}

printf(‘%s %d %.2f’, ‘adrian’, 321, Math.PI);

我们可以用 rest 操作符 … 做到同样的事情。

// ES6

function printf(format, …params) {

console.log(‘params: ‘, params);

console.log(‘format: ‘, format);

}

printf(‘%s %d %.2f’, ‘adrian’, 321, Math.PI);

展开运算符

从 apply() 到展开运算符。我们同样用 … 来解决:

提醒:我们使用 apply() 将数组转换为一列参数。例如,Math.max() 作用于一列参数,但是如果我们有一个数组,我们就能用 apply 让它生效。

正如我们较早之前看过的,我们可以使用 apply 将数组作为参数列表传递:

// ES5

Math.max.apply(Math, [2,100,1,6,43]) // 100

在 ES6 中,你可以用展开运算符:

// ES6

Math.max(…[2,100,1,6,43]) // 100

同样,从 concat 数组到使用展开运算符:

// ES5

var array1 = [2,100,1,6,43];

var array2 = [‘a’, ‘b’, ‘c’, ‘d’];

var array3 = [false, true, null, undefined];

console.log(array1.concat(array2, array3));

在 ES6 中,你可以用展开运算符来压平嵌套:

// ES6

const array1 = [2,100,1,6,43];

const array2 = [‘a’, ‘b’, ‘c’, ‘d’];

const array3 = [false, true, null, undefined];

console.log([…array1, …array2, …array3]);

字符串插值 ${}

有了模板字面量,我们就不用做多余的嵌套拼接了。来看一下:

// ES5

var first = ‘Adrian’;

var last = ‘Mejia’;

console.log(‘Your name is ’ + first + ’ ’ + last + ‘.’);

现在你可以使用反引号 (`)字符串插值 ${}

// ES6

const first = ‘Adrian’;

const last = ‘Mejia’;

console.log(
Your name is ${first} ${last}.
);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript