es6常用语法

一:let 和 const

let命令

//创建于块级作用域中
{let a = 1}

// 不存在变量提升
console.log(bar); // 报错ReferenceError
let bar = 2;

//暂时性死区(只要在代码块内使用let声明变量之前,该变量都不可用)
var tmp = 123
if(true){
    tmp = 'abc';// ReferenceError
    let tmp;
}
//在代码块内不允许重复声明变量
if(true){
  let a = 2;
  let a = 3;
}
if(true){
  let a = 2;
  var a = 3;
}

const命令

 

//const 声明一个只读的常量,一旦声明常量的值就不能改变

const PI = 234;

PI = 3 //TypeError: Assignment to constant variable.

 

 

二:变量的解构赋值

组数的结构赋值

//ES5 赋值方式

let a = 1; let b = 2; let c = 3;

//ES6 赋值方式

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

let [foo, [[bar], baz]] = [1, [[2], 3]]; //foo:1 ,bar:2,baz:3

let [x, , y] = [1, 2, 3]; // x:1, y:3

let [head, ...tail] = [1, 2, 3, 4]; // head:1, tail:[2,3,4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

// 严格来说 右边不是数组的 不是可遍历的
// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

// 对于Set结构,也可以使用结构赋值

let [x,y,z] = new Set([1,2,3])

 

对象的解构赋值

 

let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

//如果解构失败,变量的值等于undefined。
let {foo} = {bar: 'baz'};
foo // undefined

//象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。

let { log, sin, cos } = Math;

 

 

字符串的结构赋值

 

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

let {length:len} = 'hello';
console.log(len)//5

 

 

 

函数参数的结构赋值

function add([x,y]){
 return x+y
}
add([1,2])

 

能够使用圆括号的结构赋值

 

//可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号。

[(b)] = [3];

({p:(b)} = {})

[(parseInt.prop)] = [3]; // 正确
//第一行语句中,模式是取数组的第一个成员,跟圆括号无关;第二行语句中,模式是p,而不是d;第三行语句与第一行语句的性质一致。

 

 

 

三.模板字符串

 

//普通字符串
`ni hao  a  '\n' is hahahah`;

//多行字符串,会保留换行的空格,想要出去可以使用trim消去。

`In JavaScript this is
 not legal`.trim();

// 字符串中嵌入变量

let name = "Bob", time = "today";

`hello ${name} ,how are you ${time}?`

//在字符串中使用反引号``,可以用反斜杠转义

let abc = `\`Yo\` World~=!`;

 

转载于:https://www.cnblogs.com/MJ-MY/p/9395650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值