阅读 142

数组的方法及使用方法(包含ES5,ES6)

1、concat()

concat() 方法用于连接两个或多个数组。

该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。

语法:arrayObject.concat(array,......,array)

参数描述
arrayX必需。该参数可以是具体的值,也可以是数组对象。可以是任意多个。
const arr = [1,2,3]
const brr = [4,5]
const crr = [6,7]
const drr = arr.concat(brr)
const err = arr.concat(brr,crr)
console.log(drr)  //[1,2,3,4,5]
console.log(err)  //[1,2,3,4,5,6,7]复制代码

2、join()

join() 方法用于把数组中的所有元素放入一个字符串。

元素是通过指定的分隔符进行分隔的。

语法:arrayObject.join(separator)  

参数描述
separator可选。指定要使用的分隔符。如果省略该参数,则使用逗号作为分隔符。
const arr = [1,2,3]
console.log(arr.join(',')) // 1,2,3复制代码

3、pop()

pop() 方法用于删除并返回数组的最后一个元素,会改变原数组。

语法:arrayObject.pop()

const arr = [1,2,3]
const brr =arr.pop() //3
console.log(arr) //[1,2]复制代码

4、push()

push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。

语法:arrayObject.push(newelement1,newelement2,....,newelementX)

参数描述
newelement1必需。要添加到数组的第一个元素。
newelement2可选。要添加到数组的第二个元素。
newelementX可选。可添加多个元素。
const arr = [1, 2, 3]
const brr = [4, 5]
const obj = {
        name: 'shy',
        age: '24'
    }
const a = arr.push(brr) 
const b = arr.push(obj)  
console.log(arr) //[1, 2, 3, [4,5]]
console.log(arr) //[1, 2, 3, { name:'shy',age:'24'}]
console.log(arr) //[1, 2, 3, [4,5],{ name:'shy',age:'24'}]复制代码

5、reverse()

reverse() 方法用于颠倒数组中元素的顺序。

语法:arrayObject.reverse()

const arr = [1,2,'a']
const brr = arr.reverse()
console.log(brr) //['a',2,1]复制代码

6、shift()

shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。

语法:arrayObject.shift()

const arr = [1,2,3]
const brr = arr.shift()
console.log(arr) //2,3复制代码

7、slice()

slice() 方法可从已有的数组中返回选定的元素

语法:arrayObject.slice(start,end)

参数描述
start必需。规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置。也就是说,-1 指最后一个元素,-2 指倒数第二个元素,以此类推。
end可选。规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。

可使用负值从数组的尾部选取元素,如果 end 未被规定,那么 slice() 方法会选取从 start 到数组结尾的所有元素

const arr = [1,2,3]
const brr = arr.slice(0,1)
const crr = arr.slice(0)
const drr = arr.slice(0,-1)
console.log(brr)//[1]
console.log(crr) //[1,2,3]
console.log(drr) //[1,2]复制代码

8、sort()

sort() 方法用于对数组的元素进行排序。

语法:arrayObject.sort(sortby)

参数描述
sortby可选。规定排序顺序。必须是函数。
  function sortNumber(a, b) {
        return a - b
    }
    const arr = [6, 1564, 15, 234, 4, 345, 1, 5, 35, 48]
    const brr = ['Aads', 'Bd', 'AD', 'JF', 'XFG']
    console.log(brr.sort()) //["AD", "Aads", "Bd", "JF", "XFG"]
    console.log(arr.sort())  //[1, 15, 1564, 234, 345, 35, 4, 48, 5, 6]
    console.log(arr.sort(sortNumber))//[1, 4, 5, 6, 15, 35, 48, 234, 345, 1564]复制代码

9、splice()

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

语法:arrayObject.splice(index,howmany,item1,.....,itemX)

参数描述
index必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1, ..., itemX可选。向数组添加的新项目。
const arr = [1, 2, 3]
const btt = arr.splice(0,1) //删除第一项
const crr = arr.splice(0,1,"a") //替换
const drr = arr.splice(2, 0, [4, 5])//增加
console.log(arr) //[2, 3]
console.log(arr)  //["a", 2, 3]
console.log(arr)  //[1, 2,[4,5], 3]复制代码

10、toString()

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

语法:arrayObject.toString()

const arr = [1, 'a', 'SAD']
console.log(arr.toString()) //1,a,SAD复制代码

11、unshift

unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。

语法:arrayObject.unshift(newelement1,newelement2,......,newelementX)

参数描述
newelement1必需。向数组添加的第一个元素。
newelement2可选。向数组添加的第二个元素。
newelementX可选。可添加若干个元素。
const arr = [1, 2, 3]
const brr = [4, 5]
const obj = {
       name: 'shy',
       age: '22'
   }
const a = arr.unshift(brr)
const b = arr.unshift(obj)
console.log(arr) //[[4,5],1, 2, 3]
console.log(arr) //[{ name:'shy',age:'22'},1, 2, 3 ]
console.log(arr) //[ { name:'shy',age:'22'},[4,5],1, 2, 3]复制代码

ES5部分

12、Array.isArray()//判断是不是一个数组

语法:Array.isArray(arrayObject)

const arr = [1,'a',{name:'shy'}]
console.log(Array.isArray(arr)) //true复制代码

13、Array.forEach() //遍历数组

语法:array1.forEach(callbackfn[, thisArg])

参数描述
array1必选。一个数组对象。
callbackfn必选。最多可以接受三个参数的函数。对于数组中的每个元素,forEach 都会调用 callbackfn 函数一次。
thisArg可选。 callbackfn 函数中的 this 关键字可引用的对象。如果省略 thisArg,则 undefined 将用作 this 值。

回调函数的形参,依次为,value:遍历的数组内容;index:对应的数组索引,array:数组本身。

    const arr = [1, 'a', { name: 'shy' }]
    function myFunction(value, index, array) {
        //console.log(value) //1 a  {name: "shy"}
        //console.log(index)  // 0 1 2
        console.log(array)  // [1, 'a', { name: 'shy' }]  [1, 'a', { name: 'shy' }]  [1, 'a', { name: 'shy' }]
    }
    arr.forEach(myFunction)复制代码

14、Array.map() //遍历数组

语法:array1.map(callbackfn[, thisArg])

参数描述
array1必选。一个数组对象。
callbackfn必选。最多可以接受三个参数的函数。对于数组中的每个元素,forEach 都会调用 callbackfn 函数一次。
thisArg可选。 callbackfn 函数中的 this 关键字可引用的对象。如果省略 thisArg,则 undefined 将用作 this 值。

回调函数的形参,依次为,value:遍历的数组内容;index:对应的数组索引,array:数组本身。

    const arr = [1, 'a', { name: 'shy' }]
    function myFunction(value, index, array) {
        //console.log(value) //1 a  {name: "shy"}
        //console.log(index)  // 0 1 2
        //console.log(array)  // [1, 'a', { name: 'shy' }]  [1, 'a', { name: 'shy' }]  [1, 'a', { name: 'shy' }]
    }
    arr.map(myFunction)复制代码

map与forEach的异同

相同点

  • 都是循环遍历数组中的每一项

  • forEach和map方法里每次执行匿名函数都支持3个参数,参数分别是item(当前每一项),index(索引值),arr(原数组)

  • 匿名函数中的this都是指向window

  • 只能遍历数组

  • 都不会改变原数组

区别

map方法

1.map方法返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。

2.map方法不会对空数组进行检测侧,map方法不会改变原数组。

3.map支持return返回值,也不影响原数组,但是会返回一个新的数组。

4.若arr为空数组,则map方法返回的也是一个空数组。

forEach方法

1.forEach方法用来调用数组的每个元素,将元素传给回调函数。

2.forEach对于空数组是不会调用回调函数的,无论arr是不是空数组,forEach返回的都是undefined。这个方法只是将数组中的每一项作为callback的参数执行一次。

3.forEach不支持return,对原来的数组也没有影响。但是我们可以自己通过数组的索引来修改原来的数组。15、Array.filter() //过滤

语法:arr.filter(callback(element[, index[, array]])[, thisArg])

参数描述
callback必选。用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:
element数组中当前正在处理的元素。
index可选。正在处理的元素在数组中的索引。
array调用了 filter 的数组本身。
thisArg执行 callback 时,用于 this 的值
    const arr = [45, 4, 9, 16, 25];
    function myFunction(value) {
        return value > 18;
    }
   console.log(arr.filter(myFunction)) //[45, 25]复制代码

16、Array.reduce()

方法对累加器和数组中的每个元素 (从左到右)应用一个函数,将其减少为单个值。

语法:array.reduce(callbackfn,[initialValue])

reduce()方法接收callbackfn函数,而这个函数包含四个参数:

function callbackfn(preValue,curValue,index,array){}

参数描述
callback必选。回调函数
preValue上一次调用回调返回的值,或者是提供的初始值(initialValue)
curValue数组中当前被处理的数组项
index当前数组项在数组中的索引值
array调用 reduce()方法的数组
initialValue可选项,其值用于第一次调用 callback 的第一个参数。如果没有设置初始值,则将数组中的第一个元素作为初始值

空数组调用reduce时没有设置初始值将会报错

//1.数组元素求和
const arr = [1, 2, 3, 4, 5]
const brr = arr.reduce((a, b) => a+b)
console.log(brr) //15
//2.二维数组转化为一维数组
const arr = [[1, 2], [3, 4], [5, 6]]
const brr = arr.reduce((a, b) => a.concat(b),[])
console.log(brr) //[1, 2, 3, 4, 5, 6]
//3.计算数组中元素出现的次数
const arr = [1, 2, 3, 1, 2, 3, 4]
const brr = arr.reduce((items, item) => {
   if(item in items){
        items[item]++;
    }else{
        items[item] = 1;
    }
    return items;
},{}) 
console.log(brr)//{1: 2, 2: 2, 3: 2, 4: 1}
//4.数组去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5]
const brr = arr.reduce((init, current) => {
    if(init.length === 0 || init.indexOf(current) === -1){
        init.push(current);
    }
    return init;
},[]) 
console.log(brr)//[1, 2, 3, 4, 5]
//5.数组去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5]
const brr = arr.sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length-1] !== current){
        init.push(current);
    }
    return init;
},[]) //[1, 2, 3, 4, 5]console.log(brr)//6.求最大\小值 
const arr = [1,2,3,4,5]
const brr = arr.reduce((a, b) =>Math.max(a,b))
const crr = arr.reduce((a, b) =>Math.min(a,b))
console.log(brr)//5
console.log(crr)//1复制代码

17、Array.reduceRight()

方法对累加器和数组中的每个元素 (从右到左)应用一个函数,将其减少为单个值。

语法:array.reduceRight(callbackfn,[initialValue])

reduce()方法接收callbackfn函数,而这个函数包含四个参数:

function callbackfn(preValue,curValue,index,array){}

参数描述
callback必选。回调函数
preValue上一次调用回调返回的值,或者是提供的初始值(initialValue)
curValue数组中当前被处理的数组项
index当前数组项在数组中的索引值
array调用 reduce()方法的数组
initialValue可选项,其值用于第一次调用 callback 的第一个参数。如果没有设置初始值,则将数组中的第一个元素作为初始值

空数组调用reduceRight时没有设置初始值将会报错

//1.数组元素求和
const arr = [1, 2, 3, 4, 5]
const brr = arr.reduceRight((a, b) => a+b)
console.log(brr) //15
//2.二维数组转化为一维数组
const arr = [[1, 2], [3, 4], [5, 6]]
const brr = arr.reduceRight((a, b) => a.concat(b),[])
console.log(brr) // [5, 6, 3, 4, 1, 2]
//3.计算数组中元素出现的次数
const arr = [1, 2, 3, 1, 2, 3, 4]
const brr = arr.reduceRight((items, item) => {
   if(item in items){
        items[item]++;
    }else{
        items[item] = 1;
    }
    return items;
},{}) 
console.log(brr)//{1: 2, 2: 2, 3: 2, 4: 1}
//4.数组去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5]
const brr = arr.reduceRight((init, current) => {
    if(init.length === 0 || init.indexOf(current) === -1){
        init.push(current);
    }
    return init;
},[]) 
console.log(brr)//[1, 2, 3, 4, 5]
//5.数组去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5]
const brr = arr.sort().reduceRight((init, current) => {
    if(init.length === 0 || init[init.length-1] !== current){
        init.push(current);
    }
    return init;
},[]) //[1, 2, 3, 4, 5]console.log(brr)//6.求最大\小值 
const arr = [1,2,3,4,5]
const brr = arr.reduceRight((a, b) =>Math.max(a,b))
const crr = arr.reduceRight((a, b) =>Math.min(a,b))
console.log(brr)//5
console.log(crr)//1复制代码

18、Array.every()

方法用于检测数组中所有元素是否都符合指定条件,若符合返回true,否则返回false

语法:array.every(function(item,index,array){

                 //item:当前元素的值;

                    //index:当前元素的索引;

                    // array:当前元素的数组对象;

                })

every()方法使用指定函数检测数组中的所有元素;

如果数组中检测到有一个元素不满足,则整个表达式返回false,且剩余的元素不会再进行检测。如果所有元素都满足条件,则返回true;

注意 :every()不会对空数组进行检测;

every()不会改变原来的数组

    const arr = [1, 2, 3, 4, 5, 15, 456, 489, 1234]
    function checkArr(arr) {
        //   return arr>= 18;//false
        return arr>= 1; //true    }
    const brr = arr.every(checkArr)
    console.log(brr)复制代码

19、Array.some()

方法用于检测数组中的元素是否有满足指定条件的,若满足返回true,否则返回false;

语法:array.some(function(item,index,array){

//item:当前元素的值;

                    //index:当前元素的索引;

                    // array:当前元素的数组对象;

                })

some()方法会依次执行数组的每个元素;

如果有一个元素满足条件,则表达式返回true,剩余的元素不会再执行检测。如果没有满足条件的元素,则返回false

注意: some()不会对空数组进行检测;

some()不会改变原始数组;

  const arr = [1, 2, 3, 4, 5, 15, 456, 489, 1234]
    function checkArr(arr) {
        //   return arr >= 46889;//false
        return arr >= 18; //true    }
    const brr = arr.some(checkArr)
    console.log(brr)复制代码

20、Array.indexOf()

该方法返回某个元素在数组中的位置。

语法:array.indexOf(item,start)

参数: item:必需。规定需检索的字符串值。

 Start:可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

  const arr = [1,2,3,5,4,3,6,4];
      //索引值: 0 1 2 3 4 5 6 7 
     console.log(arr.indexOf(3)); //2
     console.log(arr.indexOf(3,2)); //2
     console.log(arr.indexOf("4")); //-1
     console.log(arr.indexOf(4,3)); //4复制代码

1.只有一个参数时,IndexOf从前往后找第一个item,找到就返回索引值。例如:arr.IndexOf(3)-----从z左到右找第一个3,索引值为2,所以结果就是2。

2.两个参数时,arr.IndexOf(3,2)------ 在索引 0---2之后找第一个3,其索引值为2,所以结果就是2。 arr.IndexOf(4,3)------在索引 0---3之后找第一个4,其索引值为4,所以结果就是4。

3.arr.IndexOf("4")------ 因为查找的是字符串"5",所以找不到返回 -1

 

21、Array.lastIndexOf()

该方法返回某个元素在数组中的位置。

语法:array.lastIndexOf(item,start)用法与Array.indexOf()类似

     const arr = [1,2,3,5,4,3,6,4];
        //索引值: 0 1 2 3 4 5 6 7 
     console.log(arr.lastIndexOf(3)); //5
     console.log(arr.lastIndexOf(3,2)); //2
     console.log(arr.lastIndexOf("4")); //-1
     console.log(arr.lastIndexOf(4,6)); //4复制代码

1.只有一个参数时,lastIndexOf从右向左找第一个item,找到就返回索引值。例如:arr.lastIndexOf(3)-----从右向左找第一个3,索引值为5,所以结果就是5。

2.两个参数时,arr.lastIndexOf(3,2)------在索引0---2之间找3,其索引值为2,所以结果就是2。 arr.lastIndexOf(4,6)------在索引0---6之间找4,其索引值为4,所以结果就是4

ES6

22、Array.find()

查找数组内元素,找到第一个符合条件的数组成员,返回该成员的值,如果没有找到,返回undefined

语法:arr.find(function(item,index,array){
              //item:当前元素的值;
                        //index:当前元素的索引;
                         // array:当前元素的数组对象;
                  })复制代码
const arr = [1, 2, 3, 4, 5, 6]
const brr = arr.find((value, index, arr) => {
       return value > 3 //4
       return value <-2 //undefined    })
console.log(brr) // 4复制代码

23、Array.findIndex()

Array.findIndex():找到满足条件的第一个元素,返回其位置,如果未找到,则返回-1。

语法:arr.findIndex(function(item,index,array){
          //item:当前元素的值;
                  //index:当前元素的索引;
                  // array:当前元素的数组对象;
                })复制代码
    const arr = [1, 2, 3, 4, 5, 6]
    const brr = arr.findIndex((value, index, arr) => {
        return value > 3 //3
        return value <-2 //-1    })
    console.log(brr) // 3复制代码

24、Array.from()

Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。

  那么什么是类数组对象呢?所谓类数组对象,最基本的要求就是具有length属性的对象。

  1、将类数组对象转换为真正数组:

    const arr = {

        0: 'shy',

        1: '22',

        2: [1, 2, 'a'],

        'length': 3

    }

    const brr = Array.from(arr)

    console.log(brr) //["shy", "22", [1,2,'a']]复制代码

 那么,如果将上面代码中length属性去掉呢?实践证明,答案会是一个长度为0的空数组。

  这里将代码再改一下,就是具有length属性,但是对象的属性名不再是数字类型的,而是其他字符串型的,代码如下:

    const arr = {

        'name': 'shy',

        'age': '22',

        'array': [1, 2, 'a'],

        length: 3

    }

    const brr = Array.from(arr)

    console.log(brr)  // [ undefined, undefined, undefined ]复制代码

 会发现结果是长度为3,元素均为undefined的数组

  由此可见,要将一个类数组对象转换为一个真正的数组,必须具备以下条件:

  1、该类数组对象必须具有length属性,用于指定数组的长度。如果没有length属性,那么转换后的数组是一个空数组。

  2、该类数组对象的属性名必须为数值型或字符串型的数字

  ps: 该类数组对象的属性名可以加引号,也可以不加引号

  3、将Set结构的数据转换为真正的数组: 

const arr = [1, 2, 3, 4, 5, 6]

const set = new Set(arr)

const brr = Array.from(set) 

console.log(brr)  // [1, 2, 3, 4, 5, 6]复制代码

Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如下:

 const arr = [1, 2, 3, 4, 5, 6]

 const set = new Set(arr)

 const brr = Array.from(set, item => item + 1)

 console.log(brr) // [2, 3, 4, 5, 6, 7]复制代码

3、将字符串转换为数组:

    const str = 'hello world!'

    const arr = Array.from(str)

    console.log(arr) //["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]复制代码

4、Array.from参数是一个真正的数组:

    const arr = Array.from([1, 2, 3, 4, 5, 6, 'a'])

    console.log(arr) // [1, 2, 3, 4, 5, 6, "a"]复制代码

像这种情况,Array.from会返回一个一模一样的新数组

25、Array.of(): 把一组值,转成数组

    console.log(Array.of(1, 2, 'a')) //[1, 2, "a"]

    console.log(Array.of('a')) // ["a"]

    console.log(Array.of('a').length) // 1复制代码

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

    console.log(Array()) // []

    console.log(Array(3)) // [,,,]

    console.log(Array('a')) //["a"]

    console.log(Array(1, 2, 3)) // [1, 2, 3]复制代码

上面代码中,Array方法没有参数、一个参数、三个参数时,返回结果都不一样。只有当参数个数不少于 2 个时,Array()才会返回由参数组成的新数组。参数个数只有一个时,实际上是指定数组的长度。

Array.of基本上可以用来替代Array()或new Array(),并且不存在由于参数不同而导致的重载。它的行为非常统一。

console.log(Array.of()) // []

console.log(Array.of(undefined)) // [undefined]

console.log(Array.of('a')) // ['a']

console.log(Array.of(1, 2)) // [1, 2]复制代码

Array.of()总是返回参数值组成的数组。如果没有参数,就返回一个空数组。

 

26、arr.fill() 填充

使用制定的元素填充数组,其实就是用默认内容初始化数组。

语法:arr.fill(value, start, end)

value:填充值。

start:填充起始位置,可以省略。

end:填充结束位置,可以省略,实际结束位置是end-1

无起止位置

const arr = [1, 2, 3, 4, 5]

arr.fill(7)

console.log(arr) //[7, 7, 7, 7, 7]复制代码

有开始位置

    const arr = [1, 2, 3, 4, 5]

    arr.fill(8, 2)

    console.log(arr) // [1, 2, 8, 8, 8]复制代码

有起止位置

    const arr = [1, 2, 3, 4, 5]

    arr.fill(8, 2, 3)

    console.log(arr) //  [1, 2, 8, 4, 5]复制代码

27、arr.includes()  查找指定元素是否存在,如果存在,返回true,如果不存在返回false

语法:arr.includes(searchElement, fromIndex)

searchElement:必须。需要查找的元素值。

fromIndex:可选。表示判断的起始位置。从该索引处开始查找 searchElement。

如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。

    const arr = [1, 'a', 'cj', NaN];

  console.log(arr.includes("a"));//true

    console.log(arr.includes(NaN));//true

    console.log(arr.includes("a", 0));//true

    console.log(arr.includes("a", 2));//false复制代码

1.只有一个参数时,IndexOf从前往后找第一个item,找到就返回索引值。例如:arr.IndexOf(3)   -----   从z左到右找第一个3,索引值为2,所以结果就是2。

2.两个参数时,arr.IndexOf(3,2)  ------  在索引 0---2之后找第一个3,其索引值为2,所以结果就是2。 arr.IndexOf(4,3)  ------  在索引 0--- 3之后找第一个4,其索引值为4,所以结果就是4。

3.arr.IndexOf("4")  ------  因为查找的是字符串"5",所以找不到返回 -1


作者:菜市场小石
链接:https://juejin.cn/post/7026326145410793503


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐