search
HomeWeb Front-endJS TutorialDetailed explanation of JS array usage

Detailed explanation of JS array usage

Mar 28, 2018 pm 04:31 PM
javascriptusageDetailed explanation

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor