JavaScript总结之数组篇

Array数组篇

建立

构造函数

参数为空则建立一个空数组;只有参数个数为1而且该参数为整数(参数可转换为整数)时,才会建立一个长度为当前参数值的空数组;不然参数将填充数组,充当数组内部元素。
console.log(new Array()); // []
console.log(new Array(3)); // [undefined, undefined, undefined]
console.log(new Array(Number(2))); // [undefined, undefined]
console.log(new Array('2')); // ["2"]
console.log(new Array([2])); // [[2]]
console.log(new Array({name:'rose'})); // [{name: "rose"}]
console.log(new Array(false)); // [false]
console.log(new Array(undefined)); // [undefined]
console.log(new Array(null)); // [null]
console.log(new Array(Symbol('bar'))) // [Symbol(bar)]
let attr = new Set([1,2,3,4]);
console.log(new Array(attr)); // [Set(4)]
attr = new Map([['name','jone'],['age',24]]);
console.log(new Array(attr)); // [Map(2)]
复制代码

字面量(最经常使用的一种方式)

let attr = [];
console.log(attr); // []
attr = [2];
console.log(attr); // [2]
复制代码

区别

字面量:我书写简单,而且你给我定义什么我就输出什么,谁也管不着。javascript

构造函数:不懂我就别用我。java

属性(2个属性)

Length

  • 计算数组长度算法

  • const arr = [
       {
         name:'jone',
         address:'beijing',
       },
       {
         name:'rose',
         address:'hebei',
       },
     ];
    console.log(arr.length) // 输出2
    复制代码
  • 截断数组,改变数组长度数组

  • const arr = [1,2,3,4,5];
    console.log(arr.length); // 5
    arr.length = 3;
    console.log(arr.length); // 3
    复制代码
  • 范围:0~2^32间整数bash

    • 查看数组最大长度框架

      • const attr = [];
        attr.length = Math.pow(2,32)-1; // 返回x的y次幂.
        console.log(attr.length); // 4294967295
        复制代码
    • 不在长度范围以内函数

      • const attr = [];
        attr.length = -123;
        console.log(attr.length); // error RangeError: Invalid array length
        attr.length = Math.pow() // Uncaught RangeError: Invalid array length
        复制代码

prototype

  • ​ 对原型链稍微了解一点就能看懂ui

  • const attr = new Array(6);
    console.log(Object.getPrototypeOf(attr)); 
    console.log(attr.__proto__);
    console.log(Array.prototype);
    // 都输出[constructor: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, find: ƒ, …]
    复制代码

方法(34个方法)

检测是否数组(1)

  • 不在一个全局环境下你能够千万别用我,例如多个iframe框架中穿梭,缘由:不在一个原型链,指向的内存地址不一样。spa

    • instanceofprototype

      • const attr = new Array(6);
        console.log(attr instanceof Array); // true
        复制代码
    • constructor()

      • const attr = new Array(6);
        console.log(attr.constructor === Array); // true
        复制代码
  • 无论你在哪一个环境我都行。

    • Array.isArray()

      const attr = new Array(6);
      console.log(Array.isArray(attr)); // true
      复制代码

转换为数组(2)

  • Array.from():一个相似数组可迭代对象中建立一个新的数组实例

    • 类数组对象

      // 注意:对象key必须是数字,不然转换以后的数组元素都是undefined
      // 若是不指定length属性,转换后的数组长度将默认为0
      let arrayLike = {
          '0': 'a',
          '1': 'b',
          '2': 'c',
          length: 3
      };
      console.log(Array.from(arrayLike))
      复制代码

      还有一个经典例子,就是参数arguments,可自行尝试

    • 可迭代对象

      何为可迭代对象:只要具备Symbol.iterator属性就是可迭代对象

      const s = 'hello word'; // 以字符串举例,也可尝试使用其余的数据类型
      // 具备Symbol(Symbol.iterator): ƒ [Symbol.iterator]()
      console.log(Object.getPrototypeOf(s)); 
      console.log(Array.from(s)); // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "d"]
      复制代码
  • Array.of():建立一个具备可变数量参数的新数组实例,而不考虑参数的数量或类型;我的理解与字面量方式建立数组无区别,与构造函数方式相比,惟一区别在于只有一个参数,而且参数类型为数字。

    • console.log(Array.of(3)); // [3]
      console.log(Array.of(1,2,3)); // [1,2,3]
      
      console.log(new Array(3)); // [undefined,undefined,undefined]
      console.log(new Array(1,2,3)); // [1,2,3]
      复制代码

转换为字符串(3)

  • toString():返回数组中每一个值转换为string字符串以后拼接而成的新字符串

    • var array1 = [{name:'jone'}, 2, 'a', '1a'];
      
      console.log(array1.toString()); // "[object Object],2,a,1a"
      复制代码
  • join():将一个数组(或一个类数组对象)的每一个元素调用toString方法的字符串拼接到一块儿并返回这个字符串

    • const attr = [1,2,[3,4],'helo','word',{name:'age'}];
      console.log(attr.join('_')); // "1_2_3,4_helo_word_[object Object]"
      复制代码
  • toLocaleString():与toString()方法相似,区别:这些字符串将使用一个特定语言环境的字符串

    • // 可选参数1:locales(一个 BCP 47 语言标记的字符串,或者是一个包括多个语言标记的数组。
      // 若是 locales 参数未提供或者是 undefined,便会使用运行时默认的 locale)。
      // 可选参数2:options():可自行研究
      var array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
      console.log(array1.toLocaleString('zh-Hans-CN'));
      // "1,a,1997/12/21 下午10:12:00"
      console.log(array1.toLocaleString('en'));
      //"1,a,12/21/1997, 10:12:00 PM console.log(array1.toLocaleString('en', {timeZone: "UTC"})); // "1,a,12/21/1997, 2:12:00 PM" 复制代码

栈方法(last-in-first-out)(2)

  • push(): 将一个或多个元素添加到数组的末尾,并返回该数组的新长度。(push好仍是value[]=''好呢?)

    • const attr = ['1',1,[1],{name:'jone'}];
      attr.push(2); // 添加一个
      attr.push(2,[3]);// 添加多个
      console.log(attr); // ["1", 1, [1], [object Object] {name: "jone"}, 2, 2, [3]]
      复制代码
    • push和unshifti哪一个更好呢?(固然push,由于unshift每添加一个元素就须要吧全部元素向下移一位)

      • const s = 10000;
        const p=[];
        var begin=new Date();
        for(let i = 0;i<s;i++) {
          p.push(i);
        }
        var end=new Date();
        var time=end-begin;
        console.log("time is="+time); // "time is=7"
        
        
        var begins=new Date();
        for(let i = 0;i<s;i++) {
          p.unshift(i);
        }
        var ends=new Date();
        var times=ends-begins;
        console.log("time is="+times); // "time is=31"
        复制代码
  • Pop():从数组中删除最后一个元素,并返回该元素的值影响原来数组

    • const attr = [1,2,3,4];
      const s = attr.pop();
      console.log(attr); // [1, 2, 3]
      console.log(s); // 4
      复制代码
    • pop仍是shift?(和楼上同理)

队列方法(first-in-first-out)(2)

  • unshift():方法将一个或多个元素添加到数组的开头,并返回该数组的新长度

    以块的形式插入到数组的开始位置,顺序和被做为参数传入时的顺序一致。

    let arr = [4,5,6];
    arr.unshift(1,2,3);
    console.log(arr); // [1, 2, 3, 4, 5, 6]
    
    arr = [4,5,6];
    arr.unshift(1);
    arr.unshift(2);
    arr.unshift(3);
    console.log(arr); // [3, 2, 1, 4, 5, 6]
    复制代码
  • shift():从数组中删除第一个元素,并返回该元素的值影响原数组

    var array = [1, 2, 3];
    
    var firstElement = array.shift();
    
    console.log(array,firstElement); // [2,3] 1
    
    复制代码

重排序方法(2)

  • sort():使用**原地算法(不开辟新的内存空间,操做原数组)**对数组的元素进行排序,并返回数组。

    • 无参数:元素会按照转换为的字符串的诸个字符的Unicode位点进行排序

    • // 我的理解都是获取第一个字符的unicode码而后进行排序。(有兴趣的能够看V8源码)
      const obj = {};
      const months = ['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday','Saturday','Sunday'];
      months.forEach(val=>{
        obj[val] = val.toString().charCodeAt(0);
      })
      //{Monday: 77, Tuesday: 84, Wednesday: 87, Thursday: 84, Friday: 70, …}
      console.log(obj);
      // ["Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"]
      console.log(months.sort());
      
      const strObj = {};
      const str = ['文件','编辑','试图','历史记录','书签','用户','窗口','帮助'];
      str.forEach(val=>{
        strObj[val] = val.toString().charCodeAt(0);
      })
      //{文件: 25991, 编辑: 32534, 试图: 35797, 历史记录: 21382, 书签: 20070, …}
      console.log(strObj);
      // ["书签", "历史记录", "帮助", "文件", "用户", "窗口", "编辑", "试图"]
      console.log(str.sort());
      
      
      const num = [6,70.9,65,28,80,21,87];
      const numObj = {};
      num.forEach(val=>{
        numObj[val] = val.toString().charCodeAt(0);
      })
      //{6: 54, 21: 50, 28: 50, 65: 54, 80: 56, 87: 56, 70.9: 55}
      console.log(numObj);
      // [21, 28, 6, 65, 70.9, 80, 87]
      console.log(num.sort());
      复制代码
      • 带参数:参数形式为函数,函数参数两个值,分别表明第一个和第二个用于比较的值。

        规则:第一个参数以a表示,第二个参数以b表示。

        1. 返回值<0, a 会被排列到 b 以前
        2. 返回值>0,b 会被排列到 a 以前
        3. 返回值=0, a 和 b 的相对位置不变
        var items = [
          { name: 'Edward', value: 21 },
          { name: 'Sharpe', value: 37 },
          { name: 'And', value: 45 },
          { name: 'The', value: -12 },
          { name: 'Magnetic',value: 42 },
          { name: 'Zeros', value: 37 }
        ];
        
        // 根据value值比较
        items.sort(function (a, b) {
          return (a.value - b.value)
        });
        console.log(items);
        // 根据name的第一个字符比较
        items.sort(function(a, b) {
          var nameA = a.name.charCodeAt(0);
          var nameB = b.name.charCodeAt(0);
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        });
        console.log(items);
        复制代码
  • reverse():将数组中元素的位置颠倒,并返回该数组。影响原数组

    • var items = [
        { name: 'Edward', value: 21 },
        { name: 'Sharpe', value: 37 },
        { name: 'And', value: 45 },
        { name: 'The', value: -12 },
        { name: 'Magnetic',value: 42 },
        { name: 'Zeros', value: 37 }
      ];
      
      // 根据value值比较
      items.sort(function (a, b) {
        return (a.value - b.value)
      });
      console.log(items.reverse());
      // 根据name的第一个字符比较
      items.sort(function(a, b) {
        var nameA = a.name.charCodeAt(0);
        var nameB = b.name.charCodeAt(0);
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }
        return 0;
      });
      console.log(items.reverse());
      复制代码

位置方法(2)

  • indexOf(element[, fromIndex = 0]):返回在数组中能够找到一个给定元素的第一个索引,若是不存在,则返回-1

    • const attr = ['hello','word'];
      console.log(attr.indexOf('hello'));
      复制代码
  • lastIndexOf():与indexOf正好相反。

指定值查找(2)

  • find():参数是一个回调函数,全部数组成员执行该函数,直到找到第一个返回值为true的成员,若是没有返回undefined。参数当前元素、当前索引、源数组。

    • const s = [1,2,3,4];
      const sum = s.find((element,index,source)=>{
        return element>2;
      })
      console.log(sum); // 3
      复制代码
  • findIndex():参数是一个回调函数,全部数组成员执行该函数,直到找到第一个返回值为true的成员索引,若是没有返回-1。参数当前元素、当前索引、源数组。

    • const s = [1,2,3,4];
      const sum = s.findIndex((element,index,source)=>{
        return element>2;
      })
      console.log(sum); // 2
      复制代码

迭代方法(8)

  • every:对数组的每一项运行给定函数,若是该函数对每一项都返回true,则返回true.

    • const s = [1,2,3,4];
      const s1 = s.every((item)=>item>=2);
      console.log(s1);// 返回false
      复制代码
  • some:对数组的每一项运行给定函数,只要任意一项知足条件就返回true.

    • const s = [1,2,3,4];
      const s1 = s.some((item)=>item>=2);
      console.log(s1); // true
      复制代码
  • filter:对数组中的每一项执行函数,返回该函数会返回true的项组成的新数组

    • const s = [1,2,3,4];
      const s1 = s.filter((item)=>item>=2);
      console.log(s) // [1, 2, 3, 4]
      console.log(s1); // [2, 3, 4]
      复制代码
  • forEach:对数组的每一项运行指定函数,没有返回值,和for循环相似。

    • const s = [1,2,3,4];
      const s1 = s.forEach((item)=>item>=2);
      console.log(s1); // undefined
      复制代码
  • map:对数组的每一项运行指定函数,返回指定函数返回值组成的新数组

    • const s = [1,2,3,4];
      const s1 = s.map((item)=>item+1);
      console.log(s1);//输出[2,3,4,5]
      复制代码
  • entries:返回一个包含数组中每一个索引的键/值对的Array Iterator对象。

    • const s = [1,2,3,4];
      console.log(s.entries());// Array Iterator {}
      for(let [key,values] of s.entries()){
        console.log(key+'..'+values);
      }
      复制代码
  • keys:返回一个包含数组中每一个索引键的Array Iterator对象.

    • const s = [1,2,3,4];
      console.log(s.keys()); // Array Iterator {}
      for (let key of s.keys()) {
        console.log(key); // 0 1 2 3
      }
      复制代码
  • values:返回一个包含数组中每一个索引值的Array Iterator对象.

    • const s = [1,2,3,4];
      console.log(s.values()); // Array Iterator {}
      for (let value of s.values()) {
        console.log(value); // 1 2 3 4
      }
      复制代码

归并方法(2)

  • reduce():从第一项开始,接收四个参数,累加值、当前值、当前索引、源数组,返回一个最终单个结果值

    • const s = [1,2,3,4];
      const sum = s.reduce((prev,cur,index,array)=>{
        console.log(prev+cur); // 3 6 10
        return prev+cur;
      })
      console.log(sum); // 10
      复制代码
  • reduceRight():从最后一项开始,依次向前;接收四个参数,累加值、当前值、当前索引、源数组,返回一个最终单个结果值

    • const s = [1,2,3,4];
      const sum = s.reduceRight((prev,cur,index,array)=>{
        console.log(prev+cur); // 7 9 10
        return prev+cur;
      })
      console.log(sum); // 10
      复制代码

数组填充(1)

  • fill():用一个固定值填充一个数组中从起始索引到终止索引内的所有元素,包头不包尾。返回修改后的数组

    • const s = [1,2,3,4];
      s.fill('a',1,2);
      console.log(s); // [1, "a", 3, 4]
      s.fill('b');
      console.log(s); // ["b", "b", "b", "b"]
      复制代码

拉平数组(2)

  • flat():参数为指定深度递归的值,默认为1,返回值为一个包含将数组与子数组中全部元素的新数组。

    • const s = [1,2,3,4,[2,3,4],[[3,4,5]]];
      console.log(s.flat(1)); // [1, 2, 3, 4, 2, 3, 4, [3, 4, 5]]
      console.log(s.flat(2)); // [1, 2, 3, 4, 2, 3, 4, 3, 4, 5]
      复制代码
  • FlatMap():对原数组的每一个成员执行一个函数(可理解为map函数),而后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组.

    • const s = [1,2,3,4,5];
      
      const m = s.map((element,index,source)=>{
        return element*2;
      })
      console.log(m); // [2, 4, 6, 8, 10]
      const result = s.flatMap((element,index,source)=>{
        return [element*2];
      })
      console.log(result); // [2, 4, 6, 8, 10]
      复制代码

包含某值(1)

  • includes():判断一个数组是否包含一个指定的值,根据状况,若是包含则返回 true,不然返回false。对象数组不能使用includes方法来检测。

    const s = [1,2,3,4,5];
    
    console.log(s.includes(1)); // true
    复制代码

数组合并(1)

  • concat():合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组属于浅拷贝

    • var array1 = ['a', 'b', 'c'];
      var array2 = ['d', 'e', ['g'],'f'];
      console.log(array1.concat(array2)); //["a", "b", "c", "d", "e", ["g"], "f"]
      复制代码
  • (…):使用展开操做符。此方法不会更改现有数组,而是返回一个新数组属于浅拷贝

    • var array1 = ['a', 'b', 'c'];
      var array2 = ['d', 'e', ['g'],'f'];
      
      console.log([...array1,...array2]); //["a", "b", "c", "d", "e", ["g"], "f"]
      复制代码

截取方法(1)

  • ​ slice():截取数组,包头不包尾,返回一个基于原数组浅拷贝的新数组,不影响原数组

    • const s = [1,2,3,4];
      const s1= s.slice(0,2);
      console.log(s); // [1,2,3,4]
      console.log(s1); // [1,2]
      复制代码

替换现有值(2)

  • ​ copyWithin():浅复制数组的一部分到同一数组中的另外一个位置,并返回它,不会改变原数组的长度.

    参数

    • target

      0 为基底的索引,复制序列到该位置。若是是负数,target 将从末尾开始计算。

      若是 target 大于等于 arr.length,将会不发生拷贝。若是 targetstart 以后,复制的序列将被修改以符合 arr.length

    • start

      0 为基底的索引,开始复制元素的起始位置。若是是负数,start 将从末尾开始计算。

      若是 start 被忽略,copyWithin 将会从0开始复制。

    • end

      0 为基底的索引,开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。若是是负数, end 将从末尾开始计算。

      若是 end 被忽略,copyWithin 方法将会一直复制至数组结尾(默认为 arr.length)。

    var array1 = ['a', 'b', 'c', 'd', 'e'];
    
    console.log(array1.copyWithin(0, 3, 4)); // ["d", "b", "c", "d", "e"]
    
    console.log(array1.copyWithin(1, 3)); // ["d", "d", "e", "d", "e"]
    复制代码
  • splice():经过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回删除的内容此方法会改变原数组。

    • // 删除:传递两个参数,第一个参数为数组起始位置,第二个参数表明要删除项的个数。
      var s = [1,2,3];
      console.log(s.splice(0,2));//[1, 2]
      console.log(s); // [3]
      
      // 插入:传递三个参数,第一个为起始位置,第二个为删除的个数,第三个为要插入的值,也能够有第四个第五个参数。
      console.log(s.splice(1,0,3,4,56,7)); // []
      console.log(s); // [3, 3, 4, 56, 7]
      
      // 替换:传递三个参数,第一个为起始位置,第二个为删除的个数,第三个为要插入的值,也能够有第四个第五个参数。
      console.log(s.splice(0,2,2,2)); // [3, 3]
      console.log(s); //[2, 2, 4, 56, 7]
      复制代码
相关文章
相关标签/搜索