ES6之一

4 篇文章 0 订阅
4 篇文章 0 订阅

一、let 和 const 命令

1.1、let只在代码块中生效。

{
	let x=1;
	var y=1;
}
console.log(x)	//报错,ReferenceError:a is not defined;
console.log(y)	//1

1.2、不能重复声明。

function func(){
	let a=1;
	let a = 2 ;
	console.log(a)
}
func()		//报错,Identifier 'a' has already been declared
//for循环计数器很适合let
for(let i = 1;i < 10;i++){
	setTimeout(function(){
		console.log(i)
	},1000)
}

1.3、有单独的块级作用域
1.4、const和let命令相同,有单独的块级作用域。
1.5、const声明的是常量,也和let一样不可重复声明

二、变量的解构赋值

2.1、数组的结构赋值。

let [a,b,c] = [1,2,3]	//es6新的写法
let [d,[[e],f]] = [4,[[5],6]]	//d为4,e为5,f为6
let [ , ,third] = [foo,bar,bat]	//third为bat。
let [four,...tail] = [1,2,3,4,5]	//four为1,tail为[2,3,4,5]
let [x,y,z] = new Set(["a","b","c"])	//x为a

2.2、对象的解构赋值

let {foo,bar} = {foo:'aaa',bar:'bbb'}	
foo	//"aaa"
bar	//"bbb"
let {foo} = {bar:"baz"}
foo	//undefined,如果解构失败,变量的值等于undefined。
let {foo:bar} = {foo:aaa,goa:bbb}
bar //aaa
foo	//erro:foo is no defined
let obj = {
	p:[
		'hello',
		{y:'world'}
  	]
};
let {p:[x,{y}]} = obj;
x	//"hello"
y	//"world"
p   //p is not defined,因为p这时是模式,不是变量,如果是变量的话可以写成下面这种形式。
let {p,p:[x,{y}]} = obj
p	//["hello",{y:world}]

2.3、字符串的结构赋值

const [a,b,c,d,e] = 'hello';
a	//"h"
b	//"e"
c	//"l"
d	//"l"
e	//"o"
let {length:len} = "hello"
len	//5

2.4、数值和布尔值的解构赋值

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

2.5、函数参数的解构赋值

function add([x,y]){
		return x+y
}
add([1,2])	//3
三、解构赋值的作用

3.1、变换变量的值

	let x= 1;
	let y=2;
	[x,y] = [y,x]	//变换变量的值
	

3.2、函数返回多个值

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一个对象

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

3.3、函数参数的定义

// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

3.4、提取json数据

 let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);

3.5、遍历Map结构

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

3.6、输入模块的指定方法

const { SourceMapConsumer, SourceNode } = require("source-map");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值