javascript基礎(第四天)

來源:互聯網
上載者:User

標籤:

ECMAScript6預計將在 2015年6月 正式發布

chrome測試文法需要引入Traceur編輯器https://github.com/google/traceur-compiler

瞭解未來的文法和趨勢, 未來1年內估計也用到不, 這裡只做基本的瞭解.

let 變數聲明

{
    let a = 10; //只在代碼塊內有效,適用於for,if等方法體
    var b = 20;
}
console.log(a); // ReferenceError a is not defined
console.log(b); // 20

const 聲明常量, 一旦聲明, 不可修改.

 const PI = 3.1415;

變數的解構賦值

//es3
var a = 1;
var b = 2;
var c = 3;
console.log(a); //1
console.log(b); //2
console.log(c); //3
//es6
var [x,y,z] = [4,5,6];
console.log(x); //4
console.log(y); //5
console.log(z); //6

對象的解構賦值

var {foo,bar} = {foo:‘foo‘,bar:"bbb"}; //有沒有腦殘的感覺? 

 (1)作用1,交換變數的值

[x,y] = [y,x]; 

(2)作用2,從函數返回多個值

function f(){ return [4,5,6] }
var [x,y,z] = f();
console.log(x); //4
console.log(y); //5
console.log(z); //6

(3)遍曆Map,這是我見過最簡潔的文法,後面會講到Map,for of

var map = new Map();
map.set(‘first‘,‘hello‘);
map.set(‘second‘,‘world‘);

for(let [key,value] of map){
    console.log(key+‘,‘+value);
}

字串的擴充

‘母字串‘.contains(待尋找的字串); //返回true,false, 和indexOf差不多,就傳回值不太一樣

‘母字串‘.startWith(待尋找的字串); //返回true,false,是否以什麼開頭

‘母字串‘.endsWith(待尋找的字串); //返回true,false,是否以什麼結尾

‘母字串‘.repeat(重複次數);//返回字串,是新字串?還是就舊字串? 當然是新字串啦

console.log( ‘x‘.repeat(3) ); //xxx

//下面這2個方法支援4個位元組儲存的unicode字元

‘母字串‘.codePointAt(字元索引) ; //返回編碼,用來處理大於\uFFFF的unicode字元

‘母字串‘.fromCodePoint(unicode編碼); //返回字元,用來處理大於\uFFFF的unicode字元

/匹配字串/imgu.test(待匹配的) //支援unicode, 用來處理大於\uFFFF的unicode字元

/匹配字串/imy.test(待匹配的) //隱式^  

/abcd/img.test(‘xabcd‘) === true  

/abcd/imy.test(‘xabcd‘) === false;

模板字串!!!最重要的!!!

需要反引號標示`` 支援多行輸出, 支援變數嵌入

`This is ‘abcd‘ ha ha ha`;

`he he

 ha ha

 hei hei `

var a = ‘aaa‘, b=‘bbb‘

`this is ${a} and ${b}` // this is aaa and bbb

數值的擴充

0b111110111 === 503; //支援2機制, 首碼0b

0o767 === 503; //支援8進位, 首碼0o

Number.isFinite(); //非數值,一律返回false

Number.isNaN(); 

Number.parseInt();

Number.parseFloat();

Number.isInteger();  //25 === true, 25.0 === true, 25.1 === false

Number.trunc(); 去掉小數部分 // 4.1 >> 4 , 4.9 >>4,  -4.1 >> -4, -4.9 >> -4;

Math補充了一堆數學運算方法

數組的擴充

Array.from(); //講可遍曆(set,map),或者類似數組(array-like object)轉換成真正的數組

let ps = document.querySelectorAll(‘p‘); 

Array.from(ps) == >> 轉成數組了

Array.of(); //講一組值轉換數組,

 Array.of(3,11,8); //[3,11,8];

數組執行個體.find(); //找到第一個符合的數組元素

數組執行個體.findIndex(); //找到第一個符合數字元素的索引

[1,5,10,15].findIndex(function(value,index,arr){
    return value > 9;
}); // 2

數組執行個體.fill(); //使用給定值填充一個數組

new Array(3).fill(7); //[7,7,7]

數組執行個體.entries() .keys() .values()

for(let index of [‘a‘,‘b‘].keys()){
    console.log(index);
}
for(let elem of [‘a‘,‘b‘].values()){
    console.log(elem);
}
for(let [index,elem] of [‘a‘,‘b‘].entries()){
    console.log(index+‘,‘+elem);
}

數組推導

var a1 = [1,2,3,4];
var a2 = [for (i of a1) i*2]; //[2,4,6,8] 

數組監聽(add,update,delete,splice)

Array.observe(); Array.unobserve();

對象的擴充

Object.is(); 用來比較2個值是否相等

console.log(+0 === -0); 
console.log( Object.is(+0,-0) ); //false
console.log(NaN === NaN); 
console.log( Object.is(NaN,NaN) ); //true

Object.assign(target,source1,source2,....); 將源可枚舉的屬性賦值到目標對象

 

var target = {a:1,b:1};
var source1 = {b:2,c:2};
var source2 = {c:3};
Object.assign(target,source1,source2);
target; //{a:1,b:2,c:3}

Object.__proto__ 用於讀取當前對象的prototype對象, 有了這個屬性,實際上不再需要通過Object.create()來產生對象了? 阮一峰<ECMAScript6入門>61頁

吐槽點,這個__proto__ 是否穩定? 歡迎探討

Object.setPrototypeof(); //設定原型對象

function f(obj,proto){
    obj.__proto__ = proto;
    return obj;
}
var o = f({},obj);
var o = Object.setPrototypeOf({},null); //和上面的效果一樣

Object.getPrototypeOf(待取的對象); //取得對象原型

Symbol, 一種新的未經處理資料類型, 最大的特點,就是Symbol都是不相等的

Proxy

 

var proxy = new Proxy({name:"aaaa"},{
    get:function(target/*代理對象*/,property/*屬性*/){
           return 35;
    }
});
proxy.name; //35
proxy.time; //35

Object.observe().Object.unobserve();監聽對象的變化

函數的擴充

 

function Point(x=0,y=0){ //預設值
    this.x=x;
    this.y=y;
}
var p = new Point(); //{x:0,y:0}

 

function add(...values){ //用於擷取函數的多餘參數
    let sum = 0;
    for(var val of values){
        sum += val;
    }
    return sum;
}

function push(array,...items){ // ...的用法
    array.push(...items);
}

var sum = (a,b) => a+b;  //箭頭函數
sum(3,4); //7

[1,2,3].map(x=>x*x);

Set和Map資料結構

var s = new Set(); //都是唯一的,沒有重複的值
[1,2,2,2,2,2,3].map(function(val,idx,arr){ s.add(val) });
for(var i of s){
    console.log(i);
} //1,2,3

add(value) delete(value) has(value) clear() size

var m = new Map(); //對鍵的限制不限於字串,對象也可以當鍵

 

var a = {b:‘bbb‘,c:‘ccc‘};
m.set(a,‘content‘);

size, set(key,value) get(key) has(key) delete(key) clear()  三種遍曆器 keys() values() entries(); 

var map = new WeakMap(); //只接受對象作為鍵名

Iterator和for of迴圈

Iterator遍曆器是一種規定, 有next()方法, 該方法返回{value:‘當前遍曆位置的值‘,done:布爾值,表示是否遍曆結束}

 

function mkIterator(array){
    var nextIndex = 0;
    return {
        next:function(){
            return nextIndex < array.length ?
            {value:array[nextIndex++],done:false},
            {value:undefined,done:true};
        }
    }
}

for of迴圈 一個對象

   只要部署了next方法, 就被視為具有iterator介面,就可以for of遍曆

   Array, 類數組(arguments Dom NodeList對象), Set, Map, 字串, Generator(內部狀態的遍曆器)

Generator(內部狀態的遍曆器)

Generator函數就是普通函數, 有2個特徵, 函數名後面有星號,函數體內使用yield(產出)定義遍曆器的每個成員,即不同的內部狀態

function* hellWorldGenerator(){
    yield ‘hello‘; //這個地方可以替換成函數
    yield ‘world‘;
    return ‘ending‘;
}
var h = hellWorldGenerator();
h.next(); //{value: ‘hello‘, done:false};
h.next(); //{value: ‘world‘, done:false};
h.next(); //{value: ‘ending‘, done:true};
h.next(); //{value: ‘undefined‘, done:true}; //以後再調用和這個一樣


Promise對象 !!!!這個是最好玩的!!!! 它可以將非同步操作用同步的寫法表達出來,避免了層層嵌套的回呼函數 (PromiseJS 第三方類比庫)

http://www.w3ctech.com/topic/656

http://liubin.github.io/promises-book/

Class 和 Module

class Point{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    toString(){
        return ‘(‘+this.x+‘,‘+this.y+‘)‘;
    }
}
var point = new Point(2,3);
point.toString() // (2,3)

class ColorPoint extends Point{
    constructor(x,y,color){
        super(x,y); //super.constructor(x,y)
        this.color=color;
    }
    toString(){
        return this.color+super();
    }
}

 

export 和 import

a.js

export var aaa = ‘aaa‘;

exprot var bbb = ‘bbb‘;

 

b.js

import {aaa,bbb} from ‘./a‘

console.log(aaa+‘,‘+bbb);

 

es6文法還沒有經過最佳技術實踐的檢驗, 用法不統一, 以上代碼僅供熟悉.

ECMAScript7 遙遙無期, 列舉一下吊炸天的增強

         Object.observe 對象和頁面的雙向繫結,只有其中之一發生改變,就會反應在另一面上.

         Multi-Threading 多線程支援, 讓js跑在多線程裡面(效能提升是極大的)

         Traits更好的對類的支援,

         改善記憶體回收機制/ 國際化支援/ 更多的資料結構/ 類型化更貼近硬體的低層級操作

 

未來js可能是這個星球最好的指令碼語言,沒有之一.

       它有一套風靡世界的UI架構(html+css),並且能夠適配幾乎所有螢幕,

       它能寫用戶端網頁, 也能搞伺服器通訊(node), 甚至可以寫3D(webGL), 甚至可以寫路由器外掛程式(有人小米路由掛了node),甚至可以寫手機(firefox os)等等等等

       它得到所有IT大公司的瘋狂追捧, 至今還未停止...

 

javascript基礎(第四天)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.