处理集合_创建数组


 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建数组</title>
    <script src="../unitl/test.js"></script>
    <style>
        #results li.pass {color:green;}
        #results li.fail {color:red;}
    </style>


</head>

<body>
    <ul id="results"></ul>

</body>

<script>





    //使用数组字面量[]创建数组。
    const ninjas = ["Kuma","Hattori","Yagyu"];
    //使用内置Array构造函数创建数组
    const samurai = new Array("Oda","Tomoe");


    //length属性高数我们数组的大小
    assert(ninjas.length === 3, "There are three ninjas");
    assert(samurai.length ===2, "And only two samurai");

    //通过索引访问数组元素,第一个元素的索引是0,最后一个数组的索引是数组的长度减1.
    assert(ninjas[0] === "Kuma","Kuma is the first ninja");
    assert(samurai[samurai.length - 1] === "Tomoe","Tomoe is the last samurai");


    //对超出数组世界的项,导致undefined。
    assert(ninjas[4] === undefined ,"We get undefined if we try to access an out of bounds index");


    //对超出数组边界的索引写入元素将扩充数组。
    ninjas[4] = "Ishi";
    assert(ninjas.length === 5, "Array are automatically expanded");
    


    //手动修改数组的length属性为更小数值,将会删除多余的元素。
    ninjas.length = 2;
    assert(ninjas.length ===2, "There are only two ninjas now");
    assert(ninjas[0] === "kuma" && ninjas[1] === "Hattori", "Kuma and Hattori");

    assert(ninjas[2] === undefined,"But we've lost Yagyu");





</script>
</html>



      

本例子中引入的js: test.js

在本例子中,创建了两个数组,通过数组字面量创建数组ninja:

const ninjas = ["Kuma","Hattori","Yagyu"];

数组ninjas中立即填充3个元素:Kuma,Hattori和Yagyu。数组samurai通过内置的Array构造函数创建:

const samurai = new Array("Oda","Tomoe");
     提示: 使用数组字面量创建优于数组构造函数。主要原因很简单[]与 new Array()(2个字符与11个字符(包含空格))。此外,由于javascript的高度动态特性,无法阻止修改内置的Array构造函数,
也就意味者new Array()创建的不一定是数组。因此推荐使用数组字面量。

无论使用哪种方式创建数组,每个数组都具有length属性,表示数组的长度。例如:数组ninjas的长度是3,包含3个“忍者”。我们可以这样验证:

 assert(ninjas.length===3,"There are three ninjas");
 assert(samurai.length===2,"And only two samurai");     

通过使用索引访问数组元素,第1个元素的索引是0,最后一个数组的索引是数组长度减1。但是如果视图访问数组长度范围之外的索引,例如ninjas[4],而ninjas的长度是3,
它不会像其他语言那样抛出异常,而是返回undefined。
另一方面,若在数组边界之外写入元素写入元素,例如:

      ninjas[4] = "Ishi";

数组将会扩大以适应新的形势。
与其他大多数语言不同,javaScript在length属性上,也表现出一种特殊的功能:可以手动修改length属性的值;将length值改为比原有值大的数,数组会被扩展,新扩展出的元素均为undefined;
将length改为比原有值小的数,数组会被裁剪。

原文地址:https://www.cnblogs.com/jamal/p/14060172.html