ES6基本經常使用語法

1、Let 和 const

更加優先使用let 和 const去取代varjson

2、變量的解構賦值

變量對象數組賦值

/*
let a=1;
let b={x:'test'};
let c=[1,2,3];
*/
let [a, b, c] = [1, {x: 'test'}, [1, 2, 3]];
console.log(a);  //1
console.log(b.x);  //test
console.log(c.length);  //3

默認值

let [x = '1'] = [];
console.log(x);  //1

let [y, z = '2'] = ['1'];
console.log(y);  //1
console.log(z);  //2

用途

  • 交換變量的值
let [x, y] = [1, 2];
[x, y] = [y, x];
console.log(`x=${x} y=${y}`);  //x=2 y=1
  • 提取 JSON 數據
let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data } = jsonData;

console.log(id, status, data);  // 42, "OK", [867, 5309]
  • 輸入模塊的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");

3、字符串

  • 字符串遍歷
let str='hello';
for(let i of str){
    console.log(i); 
}
/*
h
e
l
l
o
 */
  • includes(), startsWith(), endsWith()
let str='hello';
console.log(str.startsWith('he'));  //true
console.log(str.endsWith('lo'));  //true
console.log(str.includes('ll'));  //true
  • 模板字符串
let a="test";
console.log(`I am ${a}`);  //I am test

4、函數

  • rest參數
function add(...values) {
  let sum = 0;

  for (var val of values) {
    sum += val;
  }

  return sum;
}

console.log(add(2, 5, 3)) // 10
  • 箭頭函數
/*
function test(x,y){
    return x+y;
}
*/

const test=(x,y)=>x+y;

使用箭頭函數能夠避免ES5函數this的問題,箭頭函數this在方法內和方法外是同樣的數組

5、數組

  • 拓展運算符

擴展運算符(spread)是三個點(...)。它比如 rest 參數的逆運算,將一個數組轉爲用逗號分隔的參數序列函數

console.log(...[1, 2, 3])
// 1 2 3

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

6、對象

  • Object.is() 比較兩個值相等

解決==類型轉換和===的NaN不等於自身,以及+0等於-0。ui

  • Object.assign

對象的淺拷貝this

  • 對象深拷貝
JSON.parse(JSON.stringify(data));
相關文章
相關標籤/搜索