ES6新语法

let和const

//  var a = "Test1";
//  let b = "Test2";

function testVar(){
  var a = 30;
  if(true){
    var a = 50;
    console.log(a); // 50
  }

  console.log(a);  // 50
}

// testVar();

function testLet(){
  let a = 30;
  if(true){
    let a = 50;
    console.log(a);  // 50
  }
  console.log(a);   // 30
}

// testLet();

{
  let b = 100;
}

// console.log(b);

// for(var i = 0; i < 10; i++){
  // console.log(i);
// }

// console.log(i);

for(let i = 0; i < 10; i++){
  console.log(i);
}

// console.log(i);

// const
// const x = 10;
// x = 100;

const colors = [];
// colors = "Green";

colors.push("red");
colors.push("blue");

const str = "Hello";
str = "World";

console.log(colors);

模板字符串

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div class="container">
    <div id="template">
    
    </div>
  </div>
  <script src="app.js"></script>
</body>
</html>
/**
 *  模板字符串
 */

let name = "Henry";

function makeUppercase(word){
  return word.toUpperCase();
}

let template = 
  `
  <h1>${makeUppercase('Hello')}, ${name}!</h1>
  <p>感谢大家收看我们的视频, ES6为我们提供了很多遍历好用的方法和语法!</p>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
  `;

document.getElementById('template').innerHTML = template;

箭头函数

/**
 *  箭头函数
 *  解决的问题
 *  1. 缩减代码
 *  2. 改变this指向
 */

 const double1 = function(number){
    return number * 2;
 }

 const double2 = (number) => {
  return number * 2;
 }

 const double3 = (number) => number * 2;
 
 const double4 = number => number * 2;

 const double5 = (number => number * 2);
 const double6 = (number,number2) => number + number2;

 const double = (number,number2) => {
   sum = number + number2 
   return sum;
 }
//  console.log(double(20,20));

// map一个数组,让数组中的值以double形式展现
const numbers = [1,2,3];
var newNumbers = numbers.map(number => number * 2);

// console.log(newNumbers);


// 改变this指向
const team1 = {
  members:["Henry","Elyse"],
  teamName:"es6",
  teamSummary:function(){
    let self = this;
    return this.members.map(function(member){
      // this不知道该指向谁了
      return `${member}隶属于${self.teamName}小组`;
    })
  }
}

const team2 = {
  members:["Henry","Elyse"],
  teamName:"es6",
  teamSummary:function(){
    return this.members.map(function(member){
      // this不知道该指向谁了
      return `${member}隶属于${this.teamName}小组`;
    }.bind(this))
  }
}

const team = {
  members:["Henry","Elyse"],
  teamName:"es6",
  teamSummary:function(){
    return this.members.map((member) => {
      // this指向的就是team对象
      return `${member}隶属于${this.teamName}小组`;
    })
  }
}

console.log(team.teamSummary());

增强对象字面量

/**
 *  增强对象字面量
 *  解决的问题: 缩减代码
 *  
 */

// new Object(); {}
// new Array(); []

function createBookShop(inventory){
  return {
    inventory,
    inventoryValue(){
      return this.inventory.reduce((total,book) => total + book.price,0);
    },
    priceForTitle(title){
      return this.inventory.find(book => book.title === title).price;
    }
  }
}

const inventory = [
  {title:"Vue",price:10},
  {title:"Angular",price:15}
];

const bookShop = createBookShop(inventory);

// console.log(bookShop.inventoryValue());
// console.log(bookShop.priceForTitle("Angular"));


function saveFile(url,data){
  $.ajax({
    method:"POST",
    url:url,
    data:data
  });
}

const url = "http://fileupload.com";
const data = {color:"red"};

saveFile(url,data);

函数参数默认值

/**
 *  函数参数默认值
 *  优化代码
 *  
 */

// function makeAjaxRequest(url,method){
//   if(!method){
//     method = "GET";
//   }
//   return method;
// }

// function makeAjaxRequest(url,method = "GET"){
  
//   return method;
// }

// console.log(makeAjaxRequest("google.com"));
// console.log(makeAjaxRequest("google.com","POST"));

function User(id){
  this.id = id;
}
// console.log(new User(1));

function randomId(){
  return Math.random() * 99999999;
}

// console.log(new User(randomId()));

function createAdminUser(user = new User(randomId())){
  user.admin = true;
  return user;
}

const user = new User(2);

console.log(createAdminUser());

展开运算符

/**
 *  spread operator 展开运算符
 *  更快,更便捷的操作数组
 *  
 */

//  function addNumbers(numbers){
//   return numbers.reduce((sum,number) => {
//     return sum + number;
//   },0)
//  }

//  const numbers = [1,2,3,4,5];
//  console.log(addNumbers(numbers));


//  function addNumbers(a,b,c,d,e){
//   var numbers = [a,b,c,d,e];
//   return numbers.reduce((sum,number) => {
//     return sum + number;
//   },0)
//  }
//  console.log(addNumbers(1,2,3,4,5));

//  function addNumbers(...numbers){
//   return numbers.reduce((sum,number) => {
//     return sum + number;
//   },0)
//  }
//  console.log(addNumbers(1,2,3,4,5,6,7,8));

var defaultColors = ["red","greed"];
var favoriteColors = ["orange","yellow"];

// concat
// defaultColors = defaultColors.concat(favoriteColors);
// console.log(defaultColors);

// console.log([...defaultColors,...favoriteColors]);

var fallColors = ["fire red","fall orange"];

// console.log([...fallColors,...defaultColors,...favoriteColors]);
// console.log(["blue","green",...fallColors,...defaultColors,...favoriteColors]);

// 练习
function validateShoppingList(...items){
  if(items.indexOf('milk') < 0 ){
    return ["milk",...items];
  }
  return items;
}

console.log(validateShoppingList("orange","bread","eggs"));

解构(对象)

/**
 *  解构
 *  更快,更便捷
 *  
 */

//  var expense = {
//    type: "es6",
//    amount:"45"
//  };

//  var type = expense.type;
//  var amount = expense.amount;
//  console.log(type,amount);

// const { type,amount,abc } = expense;
// console.log(type,amount,abc);


var saveFiled = {
  extension: "jpg",
  name:"girl",
  size:14040
};
// es5
// function fileSammary(file){
//   return `${file.name}.${file.extension}的总大小是${file.size}`;
// }

function fileSammary({name,extension,size}){
  return `${name}.${extension}的总大小是${size}`;
}

console.log(fileSammary(saveFiled));

解构(数组-对象)

/**
 *  解构
 *  更快,更便捷
 *  
 */

// const names = ["Henry","Bucky","Emily"];
// 解构
// const [name1,name2,name3] = names;
// console.log(name1,name2,name3);

// 返回数组个数
// const {length} = names;
// console.log(length);

// 结合展开运算符
// const [name,...rest] = names;
// console.log(name);

// let a,b;

// [a,b] = [100,200];

// console.log(b);

// 对象数组
// const people = [
//   {name:"Henry",age:20},
//   {name:"Bucky",age:25},
//   {name:"Emily",age:30}
// ];

// es5 
// var age = people[0].age;
// console.log(age);

// es6 解构
// const [age] = people;
// const [{age}] = people;

// console.log(age);


// 使用场景 将数组转化为对象
const points = [
  [4,5],
  [10,1],
  [0,40]
];

// 期望数据格式
// [
//   {x:4,y:5},
//   {x:10,y:1},
//   {x:0,y:40}
// ]

// es6
// let newPoints = points.map(pair => {
//   // const x = pair[0];
//   // const y = pair[1];
//   const [x,y] = pair;
//   return {x,x}
// })

let newPoints = points.map(([x,y]) => {
  // const x = pair[0];
  // const y = pair[1];
  // const [x,y] = pair;
  return {x,y}
})

console.log(newPoints);

王如棋博客
请先登录后发表评论
  • 最新评论
  • 总共0条评论