美文网首页
引用类型 - Array 类型

引用类型 - Array 类型

作者: 小兔纸Nicole | 来源:发表于2017-05-18 19:02 被阅读0次

    Array构造函数

    当Array被当做一个函数调用时,也会创建并初始化一个新的Array对象。因此,当参数相同时,函数调用Array(...)等价于创建一个new Array(...)的表达式。

    创建数组

    1.Array()

    //创建数组
    var color = new Array();
    

    2.Array ( len )

    //创建长度为20的数组
    var color = new Array(20);
    //等价于
    var color = Array(20);
    

    3.Array ( ...items )

    //创建长度为20的数组
    0
    //等价于
    var color = Array("red", "blue", "green");
    

    通常我们使用数组字面量表示法来创建数组。数组字面量由一对包含数组的[]表示,多个数组项之间用“,”分隔。

    var color = ["red", "blue", "green"];      //创建一个包含3项的数组
    var names = [];                            //创建一个空数组
    

    Array构造函数的属性

    1.Array.from ( items [ , mapfn [ , thisArg ] ] )

    Array.from()用于将两类对象转换未真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象,其中包括ES6新增的Set和Map结构。

    let ps = document.querySelectorAll("p");
    
    Array.from(ps).forEach(function(p){
      console.log(p);
    });
    

    上面的代码中querySelectorAll方法返回的是一个类似数组的对象,只有将这个对象转换成真正的数组,才能使用forEach方法。

    Array.from()还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理。

    Array.from(arrayLike, x => x * x);
    //等同于
    Array.from(arrayLike).map( x => x * x);
    

    2.Array.isArray ( arg )

    Array.isArray() 方法用来判断某个值是否为 数组。返回布尔类型。

    3.Array.of ( ...items )

    Array.of()用于将一组数值转换为数组

    这个函数的主要目的,是弥补数组函数Array()的不足。因为参数个数的不同会导致Array()的行为有差异。

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

    Array构造函数的属性

    1.Array.prototype.concat ( ...arguments )

    concat()方法可以基于当前数组中的所有项创建一个新的数组。具体来说,这个方法会先创建当前数组一个副本,然后将接收到的参数添加到这个副本的末尾,最后返回新构建的数组。

    var colors =  ["red", "blue", "green"]; 
    var colors2 = colors.concat("yellow", ["black", "brown"]);
    
    alert(colors);              //red,blue,green
    alert(colors2);             //red,blue,green,yellow,black,brown
    

    2.Array.prototype.copyWithin ( target, start [ , end ] )

    copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。

    它接受三个参数。
    target (必需):从该位置开始替换数据。
    start (可选):从该位置开始读取数据,默认为 0 。如果为负值,表示倒数。
    end (可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。

    //  将 3 号位复制到 0 号位  
    [1, 2, 3, 4, 5].copyWithin(0, 3, 4)       // [4,2,3,4,5]  
    // -2 相当于 3 号位, -1 相当于 4 号位  
    [1, 2, 3, 4, 5].copyWithin(0, -2, -1)    // [4,2,3,4,5] 
    

    3.Array.prototype.entries ( )

    entries() 方法用于遍历数组。返回一个 Array Iterator 对象,该对象包含数组中每一个索引的键值对。

    for(let [index, elem] of ["a", "b"].entries()){
      console.log(index, elem);
    }
    // 0 "a"
    // 1 "b"
    

    4.Array.prototype.every/some ( callbackfn [ , thisArg ] )

    every()对数组中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true。some()如果有一项返回true,则返回true。

    var number = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    var everyResult = number.every(function(item, index, array){
      return (item > 2)
    });
    alert(everyResult);    //false
    
    var number = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    var someResult = number.some(function(item, index, array){
      return (item > 2)
    });
    alert(someResult);    //true
    

    5.Array.prototype.fill ( value [ , start [ , end ] ] )

    fill()使用给定值填充一个数组。fill()还可以 接收第二个和第三个参数,用于指定填充的起始位置和结束位置。

    ["a", "b", "c"].fill(7);             //[7,7,7]
    new Array(3).fill(7);                //[7,7,7]
    ["a", "b", "c"].fill(7, 1, 2);       //['a',7,'c']
    

    6.Array.prototype.filter ( callbackfn [ , thisArg ] )

    filter()对数组中的每一项运行给定函数,返回该函数会返回true的项组成的数组。

    var number = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    var filterResult = number.filter(function(item, index, array){
      return (item > 2)
    });
    alert(filterResult);    //3,4,5,4,3
    

    7Array.prototype.find ( predicate [ , thisArg ] )

    find()用于找出数组中第一个符合条件的数组元素。它的参数是一个回调函数,所有的数组元素一次遍历该回调函数,直到找出第一个返回值为true的元素,然后返回该元素,否则返回undefined。

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

    8.Array.prototype.findIndex ( predicate [ , thisArg ] )

    findIndex()用于找出数组中第一个符合条件的数组元素的位置,如果所有元素都不符合条件,返回-1。

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

    9.Array.prototype.forEach ( callbackfn [ , thisArg ] )

    forEach()对数组中的每一项运行给定函数。这个方法没有返回值。

    var number = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    number.forEach(function(item, index, array){
      //执行某些操作
    });
    

    10.Array.prototype.includes ( searchElement [ , fromIndex ] )

    includes()用来判断当前数组是否包含某指定的值,如果是,则返回true,否则false

    var a = [1, 2, 3];
    a.includes(2); // true 
    a.includes(4); // false
    

    11.Array.prototype.indexOf /lastIndexOf( searchElement [ , fromIndex ] )

    indexOf()和lastIndexOf()返回某个指定的字符串值在字符串中查找起点位置的索引。indexOf()方法从数组的开头(位置0)开始向后查找,lastIndexOf()方法则是从数组末尾开始向前查找。

    var number = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    alert(number.indexOf(4));            //3
    alert(number.lastIndexOf(4));        //5
    alert(number.indexOf(4, 4));         //5
    alert(number.lastIndexOf(4, 4));     //3
    alert(number.indexOf(8));            //-1
    

    12.Array.prototype.join ( separator )

    join() 方法用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的。

    var colors =  ["red", "blue", "green"]; 
    alert(color.join(","));        //red,green,blue
    alert(color.join("||"));       //red||green||blue
    

    如果不给join()方法传入任何参数,或者给它传入undefined,则使用“,”作为分隔符。
    13.Array.prototype.keys/values( )

    keys()是对键名的遍历,values( )是对键值的遍历。

    for(let index of ["a", "b"].keys()){
      console.log(index);
    }
    // 0 
    // 1 
    
    for(let elem of ["a", "b"].values()){
      console.log(elem);
    }
    // "a"
    // "b"
    

    14.Array.prototype.map ( callbackfn [ , thisArg ] )

    map()对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。

    var number = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    var mapResult = number.map(function(item, index, array){
      return item * 2
    });
    alert(mapResult);    //2,4,6,8,10,8,6,4,2
    

    15.Array.prototype.push/pop ( )

    栈是一种LIFO(后进先出)的数据结构。而栈中项的插入和移除只发生在一个位置 - 栈的顶部。ECMAScript为数组专门提供了push()和pop()方法,以便实现类似栈的行为。push()返回修改后的数组的长度。pop()返回数组移除项。

    var color = new Array();
    var count = color.push("red", "green");
    alert(count);           //2
    
    count = color.push("black");
    alert(count);           //3
    
    var item = color.pop();
    alert(item);            //"balck"
    alert(color.length);    //2
    

    16.Array.prototype.reduce/reduceRight ( callbackfn [ , initialValue ] )

    reduce()和reduceRight()都会迭代数组的所有项,然后构建一个最终返回的值。其中reduce()方法从数组的第一项开始,逐个遍历到最后,而reduceRight()则从数组的最后一项开始,向前遍历到第一项。两个方法都接收两个参数:一个在每一项上调用的函数和(可选的)作为归并基础的初始值。 传给reduce()和reduceRight()的函数接收4个参数:前一个值、当前值、项的索引和数组对象。

    var value = [1, 2, 3, 4, 5];
    var sum = value.reduce(function(prev, cur, index, array){
      return prev + cur;
    });
    alert(sum);             //15
    
    var value = [1, 2, 3, 4, 5];
    var sum = value.reduceRight(function(prev, cur, index, array){
      return prev + cur;
    });
    alert(sum);             //15
    

    reduceRight()和reduce()作用类似,只是方向相反。执行结果相同

    17.Array.prototype.reverse ( )

    reverse()会反转数组项的顺序

    var values = [1, 2, 3, 4, 5];
    console.log(values.reverse());     // [5, 4, 3, 2, 1]
    

    18.Array.prototype.push/shift/unshift ( )

    队列数据结构的访问规则是FIFO(先进先出)。队列在列表的末端添加,从列表的前端移除项。shift()能够移除数组中的第一项并返回数组。unshift ()shift()功能相反。和结合使用shift()和push().

    var color = new Array();
    var count = color.push("red", "green");
    alert(count);           //2
    
    count = color.push("black");
    alert(count);           //3
    
    var item = color.shift();
    alert(item);            //"red"
    alert(color.length);    //2
    
    count = color.unshift("yellow");
    alert(count );            //3
    

    19.Array.prototype.slice ( start, end )

    slice() 方法可从已有的数组中返回选定的元素。slice() 接收两个参数,即返回项的起始位置和结束位置(可选)。

    var color = Array("red", "blue", "green", "yellow", "purple");
    var color2 = color.slice(1);
    var color3 = color.slice(1,4);
    
    alert(color2);     // blue,green,yellow,purple
    alert(color3);     // blue,green,yellow
    

    20.Array.prototype.sort ( comparefn )

    sort() 方法对数组的元素做排序,并返回这个数组。即使数组中的每一项都是数值,sort()方法比较的还是字符串。

    var value = [0, 1, 5, 10, 15];
    value.sort();
    alert(value);            //0,1,10,15,5
    
    
    function sortNumber(a,b)
    {
    return a - b
    }
    alert(value.sort(sortNumber))   //0,1,5,10,15
    

    21.Array.prototype.splice ( start, deleteCount, ...items )

    splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。splice() 方法会改变原数组

    var color = Array("red", "blue", "green");
    var removed = coloe.splice(0, 1);
    alert(colors);                   //blue,green
    alert(removed);                  //red
    
    removed = coloe.splice(1, 0, "yellow", "orange");
    alert(colors);                   //blue,yellow,orange,green
    alert(removed);                  //空数组
    
    removed = coloe.splice(1, 1, "red", "purple");
    alert(colors);                   //blue,red,purple,orange,green
    alert(removed);                  //yellow
    
    

    22.Array.prototype.toString/toLocaleString ( )

    toString() 方法可把数组转换为字符串,并返回结果。toLocaleString()把数组转换为本地字符串。

    var color = Array("red", "blue", "green");
    alert(color.toString());   //red,blue,green
    
    alert(color.toLocaleString());   //red,blue,green
    
    

    参考资料

    https://tc39.github.io/ecma262/
    JavaScript高级程序设计(第3版)
    ECMAScript 6入门

    相关文章

      网友评论

          本文标题:引用类型 - Array 类型

          本文链接:https://www.haomeiwen.com/subject/qhcsxxtx.html