ES6 拾遗(1)

1. let const 不存在变量提升

2. let const 绑定到块级作用域

3. ES6 允许块级作用域无限叠加

4. ES5 中的函数只能在顶层作用域和函数作用域之中声明,不能在块级作用域中声明

5. ES6 中明确允许在块级作用域之中声明函数. ES6规定, 在块级作用域之中声明的函数在块级作用域之外不可用(类似于let)

实际情况中为了兼容旧代码

允许在块级作用域内声明函数

声明类似var, 仍然会提升到全局作用域或函数作用域的头部

同时, 函数声明还会提升到所在的块级作用域的头部

考虑到环境导致的行为差异太大, 应该避免在块级作用域内声明函数.

如果确实需要, 也应该写成函数表达式的形式

函数声明语句

{

let a = “ message “;

function f() {

return a;

}

}

函数表达式

{
let a = “ message “;

let f = function(){

return a;

}

}

6. 本质上,块级作用域是一个语句,将多个操作封装在一起, 没有返回值

7. 顶层对象在浏览器环境中指的是window对象, 在node环境中指的是global对象

8. let [a, b, c] = [1, 2, 3]

9. let [foo = true] = [ ]  // foo will be true

10. ES6 内部使用===判断一个位置是否有值, 如果一个数组成员不严格等于undefined, 默认值是不会生效的, null 不严格等于 undefined

11. 解构不仅可以用于数组,还可以用于对象

let { foo, bar } = { foo: “aaa”, bar: “bbb” };

上面的内容是下面内容的简写形式

let { foo: foo, bar: bar } = { foo: “aaa”, bar: “bbb”}

对象的解构与数组有一个重要的不同. 数组的元素是按照次序排列的, 变量的取值是由他的位置决定的; 而对象的属性没有次序, 变量必需与属性同名才能取到值

这里需要注意的是, 冒号前面的是匹配模式, 冒号后面的才是被赋值的变量

let { foo: baz} = { foo: “aaa” , bar : “bbb” };

baz // “aaa”

foo // error: foo is not defined 

真正被赋值的是baz, foo是匹配模式

12. 使用解构交换两个变量的值

Let x = 1;

Let y = 2;

[x,y] = [y,x]

13. 利用解构从函数返回多个值

数组:

function example(){

return [1,2,3];

}

let [a,b,c] = example();

对象:

function exmpale(){

return {foo:1,bar:2};

}

let {foo,bar} = example();

14. 利用解构定义函数参数

数组:

function f( [ x,y,z ] ) { … }

f( [ 1,2,3 ] )

对象:

function f( { x,y,z} ) { … }

f( { x:1,y:2,z:3} )

15. 解构模式可以用于提取JSON对象

let jsonData = {

id: 42,

status: “OK”,

data: [1,2]

};

let { id,status,data:number }

console.log( id, status, number );

// 42, “OK”, [1,2]

16. 使用解构遍历map结构

for ( let [ key,value ] of map ){

console.log( key + “is” + value );

}

获取key

for ( let [ key] of map ) { … }

获取value

for ( let [ ,value] of map ) { … }

17. 使用解构获取输入模块的指定方法

const { methodA, methodB} = require( “commonComponent”);

18. Javascript字符以UTF-16的格式存储,每个字符等于两个字节, 大于Unicode码0xFFFF的字符, Javascript会认为它是两个字符

20. 使用at()来得到正确的字符

ES5 对字符串对象提供了charAt方法, 返回字符串给定位置的字符, 该方法不能识别码点大于0xFFFF的字符

目前有一个提案提出字符串实例的at方法, 可以识别编号大于0xFFFF的字符串, 返回正确的字符

https://github.com/es-shims/String.prototype.at

npm install string.prototype.at

require('string.prototype.at');

// On Windows and on Mac systems with default settings, case doesn’t matter,
// which allows you to do this instead:
require('String.prototype.at');

21. 传统上, Javascript 中只有indexOf 方法可用来确定一个字符串是否包含在另一个字符串中

ES6 提供了3种新方法

includes() 返回布尔值,表示是否找到了参数字符串

startWith() 返回布尔值,表示参数字符串是否在源字符串的头部

endsWith() 返回布尔值,表示参数字符串是否在源字符串的尾部

22. 模板字符串

function hello() {

    let name = "lizhe";

    let a = ` hello ${name}`;

    console.log(a);

}

hello();