1. 程式人生 > >ECMAScript 6(ES6) 特性概覽和與ES5的比較16-Typed Array

ECMAScript 6(ES6) 特性概覽和與ES5的比較16-Typed Array

Typed Array

支援基於任意位元組的資料結構,以實現網路協議,加密演算法,檔案格式操作等。

ECMAScript 6

//ES6類相當於一下C結構
//例如:struct Example { unsigned long id; char username[16]; float amountDue }
class Example {
    constructor (buffer = new ArrayBuffer(24)) {
        this.buffer = buffer
    }
    set buffer (buffer) {
        this._buffer = buffer
        this._id = new Unit32Array (this.buffer, 0, 1)
        this._username = new Unit8Array (this.buffer, 4, 16)
        this._amountDue = new Float32Array (this._buffer, 20, 1)
    }
    get buffer () { return this._buffer }
    set id (v) { this._id[0] = v }
    get id () { return this._id[0] }
    set username (v) { this._username[0] = v }
    get username () { return this._username[0] }
    set amountDue (v) { this._amountDue[0] = v }
    get amountDue () {return this._amountDue[0] }
}

let example = new Example()
example.id = 7
example.username = "John Doe"
example.amountDue = 42.0

ECMAScript 5

//ES5中沒有相應表達
//  (only an equivalent in HTML5)