ES6语法学习笔记

let 命令

基本用法:
1.先定义后使用

let a = 0;
console.log(a);//a=0

2.代码块内有效
let在{}内部定义的变量,在外部是不可以访问的,而var 定义的变量是在全局范围内有效:

{
  let a = 0;
  var b = 1;
}
console.log(a);//ReferenceError: a is not defined
console.log(b);//b=0

3.不能重复声明
let 只能声明一次 ,而var 可以声明多次:

let a = 1;
let a = 2;
var b = 3;
var b = 4;
console.log(a);//Identifier 'a' has already been declared
console.log(b);//b=4

const 命令

//const声明的常量必须初始化

// const用来声明常量
 const n = 1;
// const声明的常量不允许重新赋值
// n = 2;
// const声明的常量必须初始化
//const abc;

数组的解构赋值

//基本声明
 let [a,b,c] = [1,2,3];//a=1,b=2,c=3
 //声明不附值就是undefined
 let [a,b,c] = [,123,];//a=undefined,b=123,c=undefined
 
 //添加默认值
 let [a=111,b,c] = [,123,];//a=111,b=123,c=undefined
 
//剩余运算符...
let [a, ...b] = [1, 2, 3];//a=1,b=[2, 3]

对象模型的解构

//1.对象的正常解构赋值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };// foo = 'aaa', bar = 'bbb'

//2.对象属性别名(如果有了别名,那么原来的名字就无效了)
let { baz : foo } = { baz : 'ddd' };// foo = 'ddd',baz失效

字符串的解构

//字符串在数组的解构
let [a, b, c, d, e] = 'hello';
// a = 'h', b = 'e', c = 'l', d = 'l' ,e = 'o'

字符串相关扩展

1.includes() 判断字符串中是否包含指定的字串(有的话返回true,否则返回false)
参数一:匹配的字串;参数二:从第几个开始匹配

console.log('hello world'.includes('world',7));//输出true

2.startsWith() 判断字符串是否以特定的字串开始

// let url = 'admin/index.php';
// console.log(url.startsWith('admin'));//输出true

3.endsWith() 判断字符串是否以特定的字串结束

// let url = 'admin/index.php';
 console.log(url.endsWith('php'));//输出true

4.es6字符串可以这样拼接

let obj = {
    username : '微笑',
    age : '18',
    gender : 'male'
}
// 反引号表示模板,模板中的内容可以有格式,通过${}方式填充数据
let tpl = `
    <div>
        <span>${obj.username}</span>
        <span>${obj.age}</span>
        <span>${obj.gender}</span>
        <span>${1+1}</span>
        <span>${fn('nihao')}</span>
    </div>
`;
console.log(tpl);

扩展运算符 …

剩余运算符…,相当于将剩余参数放在一个数组中,一般用于方法的调用

//1.剩余运算符...
let [a, ...b] = [1, 2, 3];//a=1,b=[2, 3]

//2.声明foo方法
function foo(a,b,c,d,e,f,g){
    console.log(a + b + c + d + e + f + g);
}
//定义数组
let arr = [1,2,3,4,5,6,7];
//调用foo方法
foo(...arr);//输出:28

箭头函数=>

箭头函数提供了一种更加简洁的函数书写方式。基本语法是:参数 => 函数体

//普通的函数
 function foo(){
     console.log('hello');
 }
 foo();
//箭头函数
 let foo = () => console.log('hello');
 foo();

当箭头函数没有参数或者有多个参数,要用 () 括起来。
/箭头函数基本用法:

//一个参数的传递
var f = v => v;
//等价于
var f = function(a){
 return a;
}
f(1);  //结果为:1

//两个参数的传递
当箭头函数没有参数或者有多个参数,要用 () 括起来。
var f = (a,b) => a+b;
f(6,2);  //8

当箭头函数函数体有多行语句,用 {} 包裹起来,表示代码块,当只有一行语句,并且需要返回结果时,可以省略 {} , 结果会自动返回。

var f = (a,b) => {
 let result = a+b;
 return result;
}
f(6,2);  // 8
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值