Home >Web Front-end >JS Tutorial >Detailed explanation of JS array usage

Detailed explanation of JS array usage

小云云
小云云Original
2018-03-28 16:31:331472browse

This article mainly shares with you the detailed explanation of JS array usage, mainly in the form of code. I hope it can help everyone.

1. Adding and deleting arrays The push() method adds one or more elements to the end of the array

    a = [];
    a.push("zero")     // a = ["zero"]
    a.push("one","two") // a = ["zero","one","two"];

The method to delete an element at the end of the array is the pop() method. The principle is to reduce the length of the array by 1 and return the deleted element.

2. join()

Array.join()方法将数组中的所有的元素转化为字符串并连接一起,返回最后生成的字符串。默认是是逗号,中间可以是任意的字符。
    var bb = ['abc','cd',1,5];
    bb.join("/")    //"abc/cd/1/5"

The Array.join() method is the reverse operation of the String.split() method, which is Split string into array.

    var str = "abc/cd/1/5";
    str.split("/")    //["abc", "cd", "1", "5"]

3、reverse()

Array.reverse()将数组中的元素顺序颠倒,
    var s = [1,2,3];
    s.reverse().join("-")   //"3-2-1"

4、sort()

对数组中的元素进行排序,返回排序后的数组。当sort()不带参数时,是按字母表排序。
    var a = new Array("banaa","apple","cherry");
    a.sort();
    var s = a.join("/");   //"apple/banana/cherry"
进行数组排序,要传递一个比较函数,假设第一个参数在前,比较函数返回一个小于0的数值,
    var a = [33,4,111,222];
    a.sort()   //111,222,33,4
    a.sort(function(a,b){return a-b});  //4,33,222,111

5 , concat()

Array.concat()方法创建并返回一个新数组,连接的数组元素,不是数组本身,concat()不会修改调用的数组
var a = [1,2,3];var b = a.concat();   数组的复制//b = [1,2,3]a.concat([4,5]);      //[1,2,3,4,5]

6, slice(). The Array.slice() method returns a fragment or subarray of the specified array. The parameters are the starting position and the ending position

    var a = [1,2,3,4,5];
    var b = a.slice(0,3)  //[1,2,3]
    a.slice(3)        //[4,5]
    a.slice(1,-1)      //[2,3,4]
    a.slice(-3,-2)     //[3]

7, splice()

Array.splice()方法在数组中插入或删除元素,不同于slice(),concat(),会修改数组。
    var a = [1,2,3,4,5,6,7,8];
    var b = a.splice(4); //a = [1,2,3,4],b=[5,6,7,8]
    var c = a.slice(1,2)  //a = [1,4] b=[2,3]
    var a = [1,2,3,4,5];
    a.splice(2,0,'a','b')  //a = [1,2,'a','b',3,4,5]

8、push()、pop()

push()在数组的尾部添加一个或者多个元素,并返回数组的新的长度。pop()删除最后一个元素,返回删除的元素。
    var stack =[];
    stack.push(1,2)   //返回2
    stack.pop()       //返回2

9、unshift()、shif()

在数组的头部进行操作,unshift()在头部添加一个或多个元素,返回长度,shift()删除数组的第一个元素,并返回
    var a = [];
    a.unshift(1,2,3,4)    //a:[1,2,3,4] 返回4
    a.shift()           //a:[2,3,4]  返回1

es5 Array methods:

遍历、映射、过滤、检测、简化、搜索数组

1, forEach()

是从头至尾遍历数组,为每个元素调用制指定的函数,该函数接收三个参数,数组元素(value)、索引(index)、数组本身(arr);
    var data = [1,2,3,4,5];
    //每个元素值自加1
    data.forEach(function(v,i,a){
        a[i] = v + 1;
    })
    //[2,3,4,5,6]

2, map()

map()方法将调用的数组的每一个元素传递给指定的函数,返回一个新数组
    a = [1,2,3];
    b = a.map(function(x){
        return x*x;
    })
    //[1,4,9]

3, filter()

filter()方法是对数组的每一个元素的,在传递函数中进行逻辑判断,该函数返回true、false
    var a = [1,2,3,4,5];
    var b = a.filter(function(x){return x < 3})  //[1,2]

4, every() and some()

every()是对所有的元素在传递函数上进行判断为true,some()是对其中的一个进行判断。
    var a = [1,2,3,4,5];
    a.every(function(x){ return x%2 === 0 })  //false,不是所有的值都是偶数
    a.some(function(x){
        return x%2 === 0;
    }) //true,a含有偶数

5, reduce() and reduceRight ()

将数组元素进行组合,生成单个值
    var a = [1,2,3,4,5];
    var sum = a.reduce(function(x,y){return x+y},0)  //数组求和
    var product = a.reduce(function(x,y){return x*y},1) //数组求积
    var max = a.reduce(function(x,y){return (x>y)?x:y})  //求最大值
    reduce()函数需要两个函数,第一个是执行简化操作的函数,第二个是初始值。

6, indexOf() and lastIndexOf()

搜索整个数组中给定的值的元素,返回找到的第一个元素的索引值,没有找到返回-1,
    var a = [0,1,2,1,0];
    a.indexOf(1)  //1
    a.lastIndexOf(1) //3
    a.indexOf(3)  //-1

es6数组方法:

1、Array.of()方法,创建一个包含所有参数的数组

    let items = Array.of(1,2);//[1,2]
    let items = Array.of(2)  //[2]
    let items = Array.of("2")//["2"]

2、Array.from(),将非数组对象转换为正式数组3、find()和findIndex()接收两个参数,一个是回调函数,另一个是可选参数,find()返回查找到的值,findeIndex()返回查找到的索引值,

let number = [25,30,35,40,45]console.log(number.find(n => n > 33))  //35console.log(number.findIndex(n => n >33)) //2

数组去重

1、遍历数组去重

function unique(obj){
    var arr = [];
    var len = obj.length;
    for(var i=0;i<len;i++){
        if(arr.indexOf(obj[i]) == -1){
            arr.push(obj[i])
        }
    }
    return arr;}unique([1,1,1,2,3])[1,2,3]

2、对象键值对法

function unique(obj){
    var tar = {},arr = [],len = obj.length,val,type;
    for(var i = 0;i<len;i++){
        if(!tar[obj[i]]){
            tar[obj[i]] = 1;
            arr.push(obj[i])
        }
    }
    return arr;}

3、es6 new Set()方法

Array.from(new Set([1,2,3,3,3])) //[1,2,3]

The above is the detailed content of Detailed explanation of JS array usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn