JavaScript之ES6常用新特性

参考:https://www.jianshu.com/p/ac1787f6c50f

变量声明:const 与 let

  const:常量,必须初始化值   let:变量

  格式:const 变量A = "值"     let 变量B = "值"  

  作用域:两者都为块级作用域

模板字符串:

  示例:

let a = "值1"

console.log(`值:${a}`)  // 输出:  值:值1

箭头函数:

  特点:1. 不需要function关键字来创建函数

     2. 当函数仅有一个表达式的时候可以省略 { } 与 return关键字

     3. 当函数只有一个参数的时候,可以省略 ()

  示例:

// 当函数主题只有一个表达式时,可以省略 {  }
let fn1 = (a, b) => a + b
// 箭头函数
let fn2 = () => {
  // 函数内容
}
// 只有一个参数可以省略 ()
let fn3 = a => {
    // 函数内容
}

函数运行参数默认值

  注意:默认值参数需要写在参数最后面

  示例:

// text2有默认值,需要写在参数的最后
function printText(text1, text2 = "123", text3 = "456") {
    console.log(`${text1}-${text2}-${text3}`)
}

printText('0000') // 输出:0000-123-456

Spread/Rest操作符( ... )

  示例:

// 示例1:当被用于迭代器中时,它是一个 Spread 操作符
function foo(x,y,z) {
  console.log(x,y,z);
}
 
let arr = [1,2,3];
foo(...arr); // 1 2 3

// 示例2:当被用于函数传参时,是一个 Rest 操作符:当被用于函数传参时,是一个 Rest 操作符:
function foo1(...args) {
  console.log(args);
}
foo1( 1, 2, 3, 4, 5);  // [1, 2, 3, 4, 5]

支持二进制和八进制字面量

let oValue = 0o10;
console.log(oValue); // 8
 
let bValue = 0b10; // 二进制使用 `0b` 或者 `0B`
console.log(bValue); // 2

对象与数组的解构

// 对象
const student = {
    name: 'Sam',
    age: 22,
    sex: '男'
}
// 数组
// const student = ['Sam', 22, '男'];

// ES5;
const name = student.name;
const age = student.age;
const sex = student.sex;
console.log(name + ' --- ' + age + ' --- ' + sex);

// ES6
const { name, age, sex } = student; // 解构
console.log(name + ' --- ' + age + ' --- ' + sex);

for...of 与 for ... in

  for...of 用于遍历一个迭代器,如数组:

let letters = ['a', 'b', 'c']
letters.size = 3for (let letter of letters) {
  console.log(letter)
}// 结果: a, b, c

  for...in 用来遍历对象中的属性:

 let stus = ["Sam", "22", "男"]
 for (let stu in stus) {
   console.log(stus[stu])
 } // 结果: Sam, 22, 男

以下两个不是特别了解:

   对象超类 super

   类 class  语法糖

一个人应养成信赖自己的习惯,即使在最危急的时候,也要相信自己的勇敢与毅力。——拿破仑

猜你喜欢

转载自www.cnblogs.com/jingxuan-li/p/11809760.html