search
HomeWeb Front-endH5 TutorialHTML5 中的新数组

Javascript中的数组是个强大的家伙:

  • 你可以创建的时候不规定长度,而是动态的去改变长度。
  • 你可以把他当成普通的数组去读取,也可以当他是堆栈来使用。
  • 你可以改变数组中每个元素的值甚至是类型。

好吧,其实他是一个对象,比如我们可以这样去创建数组:

<font size="3">var array = new Array(10);</font>

Javascript的数组的强大以及全能,给我们带来了便捷性。但一般而言:

全能的东西能在各种环境下使用,但却不一定适用于各种环境。

而TypedArray正是为了解决Javascript中数组“干太多事”而出现的。

 

起源

TypedArray是一种通用的固定长度缓冲区类型,允许读取缓冲区中的二进制数据。

其在WEBGL规范中被引入用于解决Javascript处理二进制数据的问题。

TypedArray已经被大部分现代浏览器支持,例如可以用下面方法创建TypedArray:


<font size="3">    // 创建一个8-byte的ArrayBuffer
    var b = new ArrayBuffer(8);

    // 创建一个b的引用,类型是Int32,起始位置在0,结束位置为缓冲区尾部
    var v1 = new Int32Array(b);

    // 创建一个b的引用,类型是Uint8,起始位置在2,结束位置为缓冲区尾部
    var v2 = new Uint8Array(b, 2);

    // 创建一个b的引用,类型是Int16,起始位置在2,总长度为2
    var v3 = new Int16Array(b, 2, 2);</font>

则缓冲和创建的引用布局为:

变量 索引
  字节数
b = 0 1 2 3 4 5 6 7
  索引数
v1 = 0 1
v2 =   0 1 2 3 4 5
v3 =   0 1  

这表示Int32类型的v1数组的第0个元素是ArrayBuffer类型的b的第0-3个字节,如此等等。

 

构造函数

上面我们通过ArrayBuffer来创建TypedArray,而实际上,TypedArray提供了3个构造函数来创建他的实例。

构造函数
TypedArray(unsigned long length)
创建一个新的TypedArray,length是其固定长度。
TypedArray(TypedArray array)
TypedArray(type[] array)
创建一个新的TypedArray,其每个元素根据array进行初始化,元素进行了相应的类型转换。
TypedArray(ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long length)
创建一个新的TypedArray,使其作为buffer的一个引用,byteOffset为其起始的偏移量,length为其长度。

所以通常我们用下面的方式创建TypedArray:

<font size="3">var array = new Uint8Array(10);</font>

或者:

<font size="3">var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);</font>

 

数据操作

TypedArray提供了setter、getter、set和subarray四个方法进行数据操作。

方法
getter type get(unsigned long index)

返回指定索引的元素。

setter void set(unsigned long index, type value)

设置指定索引的元素为指定值。

void set(TypedArray array, optional unsigned long offset)
void set(type[] array, optional unsigned long offset)

根据array设置值,offset为偏移位置。

TypedArray subarray(long begin, optional long end)

返回一个新的TypedArray,起始位为begin,结束位为end。

例如读取元素可以用:

<font size="3">var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
alert(array[4]);    //5</font>

设置元素可以用:

<font size="3">var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
alert(array[4]);    //5
array[4] = 12;
alert(array[4]);    //12</font>

获取一个副本可以用:

<font size="3">var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
var array2 = array.subarray(0);</font>

 

数组类型

类型 大小 描述 Web IDL类型 C 类型
Int8Array 1 8位有符号整数 byte signed char
Uint8Array 1 8位无符号整数 octet unsigned char
Uint8ClampedArray 1 8位无符号整数 (clamped) octet unsigned char
Int16Array 2 16位有符号整数 short short
Uint16Array 2 16位无符号整数 unsigned short unsigned short
Int32Array 4 32位有符号整数 long int
Uint32Array 4 32位无符号整数 unsigned long unsigned int
Float32Array 4 32位IEEE浮点数 unrestricted float float
Float64Array 8 64位IEEE浮点数 unrestricted double double

玩过canvas的可能会觉得很眼熟。

因为ImageData中用于存储图像数据的数组便是Uint8ClampedArray类型的。

例如:

<font size="3">var context = document.createElement("canvas").getContext("2d");

var imageData = context.createImageData(100, 100);

console.log(imageData.data);</font>

其在FireBug中显示为:

Uint8ClampedArray { 0=0, 1=0, 2=0, 更多...}

 

为什么要用TypedArray

我们知道Javascript中数字是64位浮点数。则对于一个二进制图片(图片每个像素点是以8位无符号整数存储的),如果要将其数据在Javascript数组中使用,相当于使用了图片8倍的内存来存储一个图片的数据,这显然是不科学的。而TypedArray能帮助我们只使用原来1/8的内存来存储图片数据。

或者对于WebSocket,如果用base64进行传输也是一个花费较高的方式,转而使用二进制传送可能是更好的方式。

当然,TypedArray还有更多好处,比如具有更好的性能,下面我们进行一些小测试来验证这一点。

参与测试的浏览器为:

FireFox 17.0.1 和 Chrome 23.0.1271.97m

  • Test1:顺序读取速读

<font size="3">var timeArray1 = [];
var timeArray2 = [];

function check1(){
    var array = new Uint8ClampedArray(5000000);
    for(var i = array.length; i--;){
        array[i] = Math.floor(Math.random() * 100);
    }
    var temp;
    var time1 = (new Date()).getTime();
    for(var i = array.length; i--;){
        temp = array[i];
    }
    var time2 = (new Date()).getTime();
    console.log(time2 - time1);
    timeArray1.push(time2 - time1);
}

function check2(){
    var array2 = new Array(5000000);
    for(var i = array2.length; i--;){
        array2[i] = Math.floor(Math.random() * 100);
    }
    var temp;
    var time3 = (new Date()).getTime();
    for(var i = array2.length; i--;){
        temp = array2[i];
    }
    var time4 = (new Date()).getTime();
    console.log(time4 - time3);
    timeArray2.push(time4 - time3);
}

function timer(__fun, __time, __callback){
    var now = 0;
    function begin(){
        var timeout = setTimeout(function(){
            if(now !== __time){
                now++;
                __fun();
                begin();
            }else{
                if(timeArray1.length && timeArray2.length){
                    console.log("timeArray1 == " + timeArray1 + ", average == " + average(timeArray1));
                    console.log("timeArray2 == " + timeArray2 + ", average == " + average(timeArray2));
                }
                __callback && __callback();
            }
        }, 100);
    }
    begin();
}

function average(__array){
    var total = 0;
    for(var i = __array.length; i--;){
        total += __array[i];
    }
    return (total / __array.length);
}

timer(check1, 10, function(){
    timer(check2, 10);
});</font>

HTML5 中的新数组

可见Uint8ClampedArray的读取速度明显比Array要快(条状柱越长,代表花费时间越多)。

  • Test2:随机读取

<font size="3">//……

function check1(){
    var array = new Uint8ClampedArray(5000000);
    for(var i = array.length; i--;){
        array[i] = Math.floor(Math.random() * 100);
    }
    var temp;
    var time1 = (new Date()).getTime();
    for(var i = array.length; i--;){
        temp = array[Math.floor(Math.random() * 5000000)];
    }
    var time2 = (new Date()).getTime();
    console.log(time2 - time1);
    timeArray1.push(time2 - time1);
}

function check2(){
    var array2 = new Array(5000000);
    for(var i = array2.length; i--;){
        array2[i] = Math.floor(Math.random() * 100);
    }
    var temp;
    var time3 = (new Date()).getTime();
    for(var i = array2.length; i--;){
        temp = array2[Math.floor(Math.random() * 5000000)];
    }
    var time4 = (new Date()).getTime();
    console.log(time4 - time3);
    timeArray2.push(time4 - time3);
}

//……</font>

HTML5 中的新数组

随即读取中Uint8ClampedArray的读取速度也是比Array要快的。

  • Test3:顺序写入

<font size="3">//……

function check1(){
    var array = new Uint8ClampedArray(5000000);
    var time1 = (new Date()).getTime();
    for(var i = array.length; i--;){
        array[i] = Math.floor(Math.random() * 100);
    }
    var time2 = (new Date()).getTime();
    console.log(time2 - time1);
    timeArray1.push(time2 - time1);
}

function check2(){
    var array2 = new Array(5000000);
    var time3 = (new Date()).getTime();
    for(var i = array2.length; i--;){
        array2[i] = Math.floor(Math.random() * 100);
    }
    var time4 = (new Date()).getTime();
    console.log(time4 - time3);
    timeArray2.push(time4 - time3);
}

//……</font>

HTML5 中的新数组

  • Test4:复制操作(U8C to U8C 和 Array to U8C)

<font size="3">//……

function check1(){
    var array = new Uint8ClampedArray(5000000);
    for(var i = array.length; i--;){
        array[i] = Math.floor(Math.random() * 100);
    }
    var temp;
    var array2 = new Uint8ClampedArray(5000000);
    var time1 = (new Date()).getTime();
    array2.set(array);
    var time2 = (new Date()).getTime();
    console.log(time2 - time1);
    timeArray2.push(time2 - time1);
}

function check2(){
    var array = new Array(5000000);
    for(var i = array.length; i--;){
        array[i] = Math.floor(Math.random() * 100);
    }
    var temp;
    var array2 = new Uint8ClampedArray(5000000);
    var time1 = (new Date()).getTime();
    array2.set(array);
    var time2 = (new Date()).getTime();
    console.log(time2 - time1);
    timeArray2.push(time2 - time1);
}

//……</font>

HTML5 中的新数组

可见U8C复制到U8C,比Array复制到U8C快得多。

 

参考文献

Typed Array Specification

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.