js 数组操作集锦

415 阅读5分钟

数组常用的基本方法

一、 数组的属性:
constructor 返回(数组,数字,字符串等)对象原型创建的函数。
length 设置或返回数组元素的个数。
prototype 是js全局属性,允许你向(数组,函数,stringd等)对象添加属性或方法。

码子展示以上三个属性:

1. constructor :
返回值:一个函数对象。该函数由(数组,数字,字符串)对象的原始创建。

[1,2,3,4].constructor
Number.constructor
'1234'.constructor
输出:function Array() { [native code] }
      function Number() { [native code] }
      function String() { [native code] }
      
2.prototype :  Array属性构造器
我们用prototype为Array构造一个方法,为处理数组提供一个公用的功能
Array.prototype.gets = function () {
    this.forEach(function (val) {
        console.log(val) //1234
        //这里this代表数组
    })
}
调用运行构建的方法:
sets([1,2,3,4]);
sets([1])
function sets (item) {
    item.gets();    
}

我们用prototype为Array构造一个属性:当构建一个属性,所有的数组将被设置属性,它是默认值。
  Array.prototype.name = 'val';给所有的数组设置属性name
  [1,2].name  //输出val

二、数组的方法: 直接上图: 根据上图,我们对数组的方法进行归类下:

  1. 不会改变原数组的方法:
arr.slice()
arr.map()
arr.forEach()
arr.every()
arr.some()
arr.filter()
arr.reduce()
arr.entries()
arr.find()
arr.concat()
  1. 能改变原数组的方法:
arr.splice()
arr.reverse()
arr.fill()
arr.copyWithin()
arr.sort()
arr.push()
arr.pop()
arr.unshift()
arr.shift()
  1. es5以后新增的方法
 copyWithin()     
 entries()   
 fill()    
 find()
 findIndex() 
 from() 
 keys() 
 以上方法兼容ie12+
 includes() 兼容 ie14+

现在我们对es5以后新增的方法操作下:

array.copyWithin(target, start, end)
参数:
target	必需。复制到指定目标索引位置。
start	可选。元素复制的起始位置。
end	可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。
复制'qq'替换数组最后一位4
[1,2,'3','qq',4].copyWithin(-1,3,4) //[1,2,'3','qq','qq']
复制1,2替换数组后两位'qq',4
[1,2,'3','qq',4].copyWithin(3,0,-1) //[1, 2, "3", 1, 2]
-----------------------------------------------------------------------
entries() 返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)。
参数:无
迭代对象中数组的索引值作为 key, 数组元素作为 value。
 [0, "1"]
 [1, "2"]
 [2, "3"]
var x = ['1','2','3'].entries();
    x.next().value // [0, "1"]
    x.next().value //  [1, "2"]
----------------------------------------------------------------------    
fill() 方法用于将一个固定值替换数组的元素。
参数
value	必需。填充的值。
start	可选。开始填充位置。
end	可选。停止填充位置 (默认为 array.length)

用 '啦啦'替换数组的第二项'嗯嗯'
['哈哈','嗯嗯','哦哦'].fill('啦啦',1,2);
//["哈哈", "啦啦", "哦哦"]
----------------------------------------------------------------------
find() 方法返回通过测试(函数内判断)的数组的第一个(注意第一个)元素的值。
       为数组中的每个元素都调用一次函数执行:
       
参数:
function(currentValue, index,arr)	必需。数组每个元素需要执行的函数。
函数参数:
currentValue	必需。当前元素
index	可选。当前元素的索引值
arr	可选。当前元素所属的数组对象
thisValue	可选。 传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值 
当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
如果没有符合条件的元素返回 undefined

我们来一个返回数组中符合 >6的第一个元素
function finds (x) {
    return this > 6
}
 
var a = [1,2,3,4,7,8];
console.log(a.find(finds)) //7
------------------------------------------
findIndex和find不同的是:
    (1).当数组中的元素在测试条件,如果没有符合条件的元素则返回 -1
    (2)返回通过测试(函数内判断)的数组的第一个元素的索引值(从0开始计算)
    console.log(a.findIndex(finds)) //4  输入数组中第一个为7的元素的索引
-----------------------------------------------------------
from() 方法用于通过拥有 length 属性的对象或可迭代的对象来返回一个数组。
如果对象是数组返回 true,否则返回 false。

Array.from(object, mapFunction, thisValue);
参数 
object	必需,要转换为数组的对象。
mapFunction	可选,数组中每个元素要调用的函数。
thisValue	可选,映射函数(mapFunction)中的 this 对象。

例:
将字符串转成数组:Array.from("hello")  // [h,e,l,l,o]
为要转换成数组的字符操作: Array.form('hello',(x) => x + 1) //["h1", "e1", "l1", "l1", "o1"]
将类数组转为数组: Array.from({0:1,1:2,2:3,length:3}) //[1,2,3]
      或者这样写: Array.from({length:3}).map((val,i) => i + 1)  //[1,2,3]
--------------------------------------------------------------------------
keys() 方法用于从数组创建一个包含数组键的可迭代对象。 对对象数组不生效
如果对象是数组返回 true,否则返回 false。
参数:无
例:
返回元素索引:var x = [1,2,3].keys()   Array Iterator {} //返回原型对象的迭代器 
                x.next().value //0    
                x.next().value //1
                x.next().value //2
        注: next()方法返回keys的迭代对象{value: 2, done: false}

           
 -------------------------------------------------------------------------
 includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。
 参数 
searchElement	必须。需要查找的元素值。
fromIndex	可选。从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。
检索[1,2,3]中是否有1: 
            直接检索:[1,2,3].includes(1) //true
            按索引开始位置检索: [1,2,3].includes(1,0) //true
        
    注意:如果fromIndex 大于等于数组长度 ,则返回 false 。该数组不会被搜索:
            [1,2,3].includes(3,3) //false
    注意: 如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索
         [1,2,3].includes('a', -100); // true
    

数组去重集结

原数组:var arr = [1,2,3,3,3,4,5.6,5.6,0,9];

1.indexOf或lastIndexOf去重

var newArr = [];
arr.forEach((val,index) => {
   newArr.indexOf(val) === -1 ? newArr.push(val) : '';
});
console.log(newArr)//[1, 2, 3, 4, 5.6, 0, 9]

2.ES6 newSet去重

    Array.from(newSet(arr));//[1, 2, 3, 4, 5.6, 0, 9]

3.通过filter过滤返回一个新数组在原数组中对比用indexof去重

let arr = [1,8,9,4,5,1,2,3,8,9,10]
let newArr = arr.filter((item,index,self) =>{
    return self.indexOf(item) === index; //比较数组中每一项是否为其(indexof)首次查找的索引值(index)
})

数组排序集结

1.冒泡排序

数组基本