ES6學(xué)習(xí)筆記

圖片來源:https://ss2.bdstatic.com

let與var

  • 同一個(gè)作用域里,如果命名重復(fù)的話,var后者會覆蓋掉前者,而let會報(bào)錯(cuò)
// var直接覆蓋
var temp = 1;
console.log(temp);  // 1
var temp = 2;
console.log(temp);  // 2
// let報(bào)錯(cuò)
let temp = 1;
console.log(temp);
let temp = 2;
console.log(temp); // Uncaught SyntaxError: Identifier 'temp' has already been declared
  • var只有全局作用域和函數(shù)作用域,let相較于var增加了塊作用域
var name1 = 'aaaaa';
while (true) {
    var name1 = 'bbbbb';
    console.log(name1); // bbbbb
    break;
}
console.log(name1);  // bbbbb, while里的name1值覆蓋了外面所定義的name1值
let name2 = 'aaaaa';
while (true) {
    let name2 = 'bbbbb';
    console.log(name2); // bbbbb
    break;
}
console.log(name2) // aaaaaa, while里的name2值不會覆蓋外面所定義的name2值
  • let解決了var的變量泄露問題,var一般使用閉包來解決這個(gè)問題
var a1 = [];
for (var i = 0; i < 10; i++) {
    a1[i] = function () {
        console.log(i);
    };
}
a1[6]();  // 10
a1[3]();  // 10
let a2 = [];
for (let i = 0; i < 10; i++) {
    a2[i] = function () {
        console.log(i);
    };
}
a2[6](); // 6
a2[3](); // 3

const

  • 同一個(gè)作用域里,如果命名重復(fù)的話會報(bào)錯(cuò),不同作用域里會不影響
for(var i = 0; i < 2; i++){
    const PI = Math.PI; 
    console.log(PI);  // 3.141592653589793
}
const PI = 3.14;
console.log(PI); // 3.14
  • const定義常量,值不能改變
const PI = Math.PI;
PI = 23; // Uncaught SyntaxError: Identifier 'PI' has already been declared
  • const允許變量賦值
let te1 = 1;
const text = te1;
console.log(text); // 1
te1 = 2;
console.log(text); // 2
  • const的實(shí)際用途
// 定義常量
const PI = Math.PI;
// 定義函數(shù)
const fun1 = () => {
    ...
}
// 命名空間
const GLOBAL = {}
GLOBAL.namespace = function (str) {
        var arr = str.split('.'),
    o = GLOBAL;
    for(let i = (arr[0] === 'GLOBAL') ? 1 : 0; i < arr.length; i++){
            o[arr[i]] = o[arr[i]] || {};
            o = o[arr[i]];
    }
};

面向?qū)ο?/h2>
  • class, extends, super
function Point(x, y) {
    this.x = x;
    this.y = y;
}
Point.prototype.toString = function () {
    return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
//定義類
class Point {
    constructor(x, y) {    //constructor 構(gòu)造方法
        this.x = x;
        this.y = y;
    }
    toString() {
        return '(' + this.x + ', ' + this.y + ')';
    }
}
var p = new Point(1, 2);

arrow function 箭頭函數(shù)

  • 簡化代碼,指向使用時(shí)所在的對象。
  • 解決了 this 指向亂跑的問題。
  • 備注
    • 如果只有一個(gè)參數(shù)時(shí) () 可以省略
    • 如果只有一個(gè)return時(shí) {}return 可以省略
function test1(x, y) { 
    x++;
    y--;
    return x + y;
}
const test2 = (x, y) => {
    x++; 
    y--; 
    return x+y
}
function test3(x) => {
    return x * 3;
}
const test4 = x => x * 3;
  • 實(shí)例
<div class="red">
    <div class="blue">
    </div>
</div>
<script type="text/javascript">
    $('.red').on('click', clickEvent);
    function clickEvent(){
        var that = this;
        //$(this).text();
        console.log(this);
        // $(this).text('被點(diǎn)擊了');
        setTimeout(function(){
            $(that).text('被點(diǎn)擊了');
            console.log(this);
        }, 1000);
        setTimeout(() => {
            $(this).text('被點(diǎn)擊了');
            console.log(this);
        }, 1000);
    }
    // function clickEvent(){
    //  var that = this;
    //  console.log(this);
    //  changeEvent();
    //  function changeEvent(){
    //      console.log(this);
    //      $(that).find('.blue').css('background-color', 'yellow');
    //  }
    //  const changeEvent = () => {
    //      $(this).find('.blue').css('background-color', 'yellow');
    //  }
    // }
</script>

string 字符串

新方法

  • startsWith
  • endsWith

template string 字符串模板

<div id="result1"></div>
<div id="result2"></div>
let basket = {
    count: 5,
    onSale: 4
};
$("#result1").append(
    "There are <b>" + basket.count + "</b> " +
    "items in your basket, " +
    "<em>" + basket.onSale +
    "</em> are on sale!"
);
$("#result2").append(`
    template string:
    There are <b>${basket.count}</b> items
    in your basket, <em>${basket.onSale}</em>
    are on sale!
`);
className="";
className={`class1 clsaa2`};

destructuring 解構(gòu)賦值

  • 簡化代碼
  • 注意
    • 等號兩邊結(jié)構(gòu)必須一樣
    • 聲明和賦值不能分開
let cat = '喵喵';
let dog = '旺財(cái)';
let zoo1 = {cat: cat, dog: dog};
console.log(zoo1);  // {cat: '喵喵', dog: '旺財(cái)'}
let zoo2 = {cat, dog};
console.log(zoo2);  // {cat: '喵喵', dog: '旺財(cái)'}
let { type, many} = {type: 'animal', many: 2};
console.log(type, many); // animal 2

default,rest

  • 給參數(shù)一個(gè)默認(rèn)值 type = 'cat' ,之前都是用 type = type || 'cat' 實(shí)現(xiàn)
  • rest 用于收集剩余的參數(shù)
  • rest 也可用于數(shù)組展開
  • rest 必須是最后一個(gè)形參
function todo(type = 'cat', b , ...arg){
    console.log(type, b, arg);
}
todo(undefined, '123', [1,2,3], 12); // cat 123 [[1, 2, 3], 12]

數(shù)組處理

map 映射(一對一)

// 統(tǒng)一用 arr 做例子
let arr = [
    { name: '張三', score: 30 },
    { name: '李四', score: 96 },
    { name: '喵喵', score: 59 },
];
const introduce = arr.map(val => `${val.name}考了${val.score},${val.score < 60 ? '不' : ''}及格`);
console.log(introduce.join(';')); // 張三考了30,不及格;李四考了96,及格;喵喵考了59,不及格

reduce 匯總(多對一)

  • 形參
    • tmp 中間結(jié)果
    • item 本次數(shù)據(jù)
    • index 下標(biāo),從1開始
const max = arr.reduce((tmp, item, index) => {
    console.log(tmp, item, index);
    // {name: "張三", score: 30} {name: "李四", score: 96} 1
    //  {name: "李四", score: 96} {name: "喵喵", score: 59} 2
    return tmp.score > item.score ? tmp : item;
});
console.log(`${max.name}考的分?jǐn)?shù)最高,最高分為${max.score}`); // 李四考的分?jǐn)?shù)最高,最高分為96

filter 過濾

const noPass = arr.filter(val => {
    return val.score < 60;
});
console.log(`${noPass.map(v => v.name)}未及格,需要請家長`); // 張三,喵喵未及格,需要請家長

forEach 迭代

  • 簡化代碼,但是不能在forEach中使用break、continue、return關(guān)鍵字
arr.forEach((val) => {
    console.log(val); 
    // { name: '張三', score: 30 },
    // { name: '李四', score: 96 },
    // { name: '喵喵', score: 59 },
});

for-in與for-of

for-in是為普通對象設(shè)計(jì)的,適用于遍歷得到字符串類型或者對象的鍵,而不適用于數(shù)組遍歷。
在使用for-in遍歷數(shù)組時(shí)會出現(xiàn)以下問題:

  1. for(let k in arr)k的值不是數(shù)字而是字符串"0"、"1"、"2"
  2. for-in循環(huán)體除了遍歷數(shù)組元素外,還會遍歷自定義屬性,甚至連數(shù)組原型鏈上的屬性都能被訪問到
  3. 在某些情況下,for-in可能按照隨機(jī)順序遍歷數(shù)組元素

由于在使用for-in遍歷數(shù)組會出現(xiàn)一些問題,所以ES6增加了for-of: 語法簡潔,修復(fù)for-in的問題,可以使用break、continuereturn關(guān)鍵字(相比于forEach)

let arr = ['1', '2', '3'];
for(let i of arr){
    console.log(i);
}
  • 支持遍歷DOM NodeList(for-in遍歷得到的并不是子節(jié)點(diǎn))
<div id="parent">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
    <span>5</span>
</div>
<script>
    let parent = document.getElementById('parent');
    let child_nodes = parent.childNodes;
    for(let node of child_nodes){  
        console.log(node);
    }
    // 相當(dāng)于
    for(let i = 0; i < child_nodes.length; i++){
        console.log(child_nodes[i]);
    }
</script>
  • 支持字符串的遍歷,會把字符串作為一組 Unicode 的字符進(jìn)行遍歷(for-in也可以做到)
for (var ch of "123") {
    console.log(ch);
}
  • 還支持應(yīng)用于 Map 和 Set 對象(Map 和 Set 對象還沒研究,暫擱)

  • 注意: for-of并不適用于處理原有的原生對象(包括JSON對象),處理原有的原生對象時(shí)可以使用for-in或者內(nèi)置的Object.keys()

let obj = {
    name: '張三',
    age: 12
}
for(let key in obj){
    console.log(key, obj[key]);
}
for (var key of Object.keys(obj)) {
    console.log(key, obj[key]);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容