search
HomeWeb Front-endJS TutorialDetailed explanation of the method of creating arrays in js that must be mastered (pure code)

There are many ways to create arrays in js, which ones do you know? Specifically look at these:

join(), push() and pop(), shift() and unshift(), sort(), reverse(), concat(), slice(), splice (), indexOf() and lastIndexOf() (new in ES5), forEach() (new in ES5), map() (new in ES5), filter() (new in ES5), every() (new in ES5) ), some() (new in ES5), reduce() and reduceRight() (new in ES5)

// 1、join(separator): 将数组的元素组起一个字符串,以separator为分隔符,省略的话则用默认用逗号为分隔符,
    // 该方法只接收一个参数:即分隔符。原数组不变
    var arr = [1, 2, 3];
    console.log(arr.join()); // 1,2,3
    console.log(arr.join("-")); // 1-2-3
    console.log(arr); // [1, 2, 3](原数组不变)

    // 2.push(): 添加到数组末尾,返回新数组。 参数最少一个
    // pop():数组末尾移除最后一项,返回新数组
    var arr = ["Lily", "lucy", "Tom"];
    var count = arr.push("Jack", "Sean");
    console.log(count); // 5
    console.log(arr); // ["Lily", "lucy", "Tom", "Jack", "Sean"]
    var newArr = ["Lily", "lucy", "Tom", "Jack", "Sean"]
    var item = newArr.pop();
    console.log(item); // Sean
    console.log(newArr); // ["Lily", "lucy", "Tom", "Jack"]

    // 3.shift():删除原数组第一项,返回新数组 。 
    // unshift:将参数添加到原数组开头,返回新数组 。
    var arrSh = ["Lily", "lucy", "Tom"];
    var countSh = arrSh.unshift("Jack", "Sean");
    console.log(countSh); // 5
    console.log(arrSh); //["Jack", "Sean", "Lily", "lucy", "Tom"]
    var newArrSh = ["Jack", "Sean", "Lily", "lucy", "Tom"]
    var itemSh = newArrSh.shift();
    console.log(itemSh); // Jack
    console.log(newArrSh); // ["Sean", "Lily", "lucy", "Tom"]

    // 4.sort():按升序排列数组项——即最小的值位于最前面,最大的值排在最后面。
    var arr1 = ["ad", "dg", "c", "b"];
    console.log(arr1.sort()); // ["ad", "b", "c", "dg"]
    arr2 = [13, 24, 51, 3];
    console.log(arr2.sort()); // [13, 24, 3, 51]
    console.log(arr2); // [13, 24, 3, 51](元数组被改变)
    // 排序
    function compare(val1, val2) {
      return val1 - val2
    }
    console.log(arr2.sort(compare)) //[3, 13, 24, 51]

    // 5.reverse():反转数组项的顺序。
    var arrNum = [13, 24, 51, 3];
    console.log(arrNum.reverse()); //[3, 51, 24, 13]
    console.log(arrNum); //[3, 51, 24, 13](原数组改变)

    // 6.concat()  原数组没有变
    var arrC = [1, 3, 5, 7];
    var arrCopy = arrC.concat(9, [11, 13]);
    console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]
    console.log(arrC); // [1, 3, 5, 7](原数组未被修改)

    var arrCopy2 = arrC.concat([9, [11, 13]]);
    console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]
    console.log(arrCopy2[5]); //[11, 13]

    // 7.slice() (原数组没变)
    // slice():返回从原数组中指定开始下标到结束下标之间的项组成的新数组。slice()方法
    // 可以接受一或两个参数,即要返回项的起始和结束位置。
    // 在只有一个参数的情况下, slice()方法返回从该参数指定位置开始到当前数组末尾的所
    // 有项。如果有两个参数,该方法返回起始和结束位置之间的项——
    // 但不包括结束位置的项。
    var arr = [1, 3, 5, 7, 9, 11];
    var arrCopy = arr.slice(1);
    var arrCopy2 = arr.slice(1, 4);
    var arrCopy3 = arr.slice(1, -2);
    var arrCopy4 = arr.slice(-4, -1);
    console.log(arr); //[1, 3, 5, 7, 9, 11](原数组没变)
    console.log(arrCopy); //[3, 5, 7, 9, 11]
    console.log(arrCopy2); //[3, 5, 7]
    console.log(arrCopy3); //[3, 5, 7]
    console.log(arrCopy4); //[5, 7, 9]

    // 8.splice() (原数组改变了)
    // splice():很强大的数组方法,它有很多种用法,可以实现删除、插入和替换。
    // 删除: 可以删除任意数量的项, 只需指定 2 个参数: 要删除的第一项的位置
    // 和要删除的项数。 例如, splice(0, 2) 会删除数组中的前两项。
    // 插入: 可以向指定位置插入任意数量的项, 只需提供 3 个参数: 起始位置、 
    // 0( 要删除的项数) 和要插入的项。 例如, splice(2, 0, 4, 6)
    //  会从当前数组的位置 2 开始插入4和6。
    // 替换: 可以向指定位置插入任意数量的项, 且同时删除任意数量的项, 只需指
    // 定 3 个参数: 起始位置、 要删除的项数和要插入的任意数量的项。 
    // 插入的项数不必与删除的项数相等。 例如, splice(2, 1, 4, 6) 会删除当前
    // 数组位置 2 的项, 然后再从位置 2 开始插入4和6。
    // splice() 方法始终都会返回一个数组, 该数组中包含从原始数组中删除的项,
    //  如果没有删除任何项, 则返回一个空数组
    var arr = [1, 3, 5, 7, 9, 11];
    var arrRemoved = arr.splice(0, 2);
    console.log(arr); //[5, 7, 9, 11]
    console.log(arrRemoved); //[1, 3]
    var arrRemoved2 = arr.splice(2, 0, 4, 6);
    console.log(arr); // [5, 7, 4, 6, 9, 11]
    console.log(arrRemoved2); // []
    var arrRemoved3 = arr.splice(1, 1, 2, 4);
    console.log(arr); // [5, 2, 4, 4, 6, 9, 11]
    console.log(arrRemoved3); //[7]

    // 9、indexOf()和 lastIndexOf()
    // indexOf():接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中,
    //  从数组的开头(位置 0)开始向后查找。 
    // lastIndexOf:接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中,
    //  从数组的末尾开始向前查找。
    // 这两个方法都返回要查找的项在数组中的位置,或者在没找到的情况下返回1。在比较第一
    // 个参数与数组中的每一项时,会使用全等操作符。
    var arr = [1, 3, 5, 7, 7, 5, 3, 1];
    console.log(arr.indexOf(5)); //2
    console.log(arr.lastIndexOf(5)); //5
    console.log(arr.indexOf(5, 2)); //2
    console.log(arr.lastIndexOf(5, 4)); //2
    console.log(arr.indexOf("5")); //-1

    // 10.forEach():对数组进行遍历循环,对数组中的每一项运行给定函数。这个方法没有返回值。
    // 参数都是function类型,默认有传参,参数分别为:遍历的数组内容;第对应的数组索引,数组本身。
    var arr = [1, 2, 3, 4, 5];
    arr.forEach(function (x, index, a) {
      console.log(x + '|' + index + '|' + (a === arr));
    });
    // 输出为:
    // 1|0|true
    // 2|1|true
    // 3|2|true
    // 4|3|true
    // 5|4|true

    // 11.map():指“映射”,对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
    var arr = [1, 2, 3, 4, 5];
    var arr2 = arr.map(function (item) {
      return item * item;
    });
    console.log(arr2); //[1, 4, 9, 16, 25]

    // 12.filter():“过滤”功能,数组中的每一项运行给定函数,返回满足过滤条件组成的数组。
    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var arr2 = arr.filter(function (x, index) {
      return index % 3 === 0 || x >= 8; //index 是下标  x是每一项
    });
    console.log(arr2); //[1, 4, 7, 8, 9, 10]

    // 13.every():判断数组中每一项都是否满足条件,只有所有项都满足条件,才会返回true。
    var arr = [1, 2, 3, 4, 5];
    var arr2 = arr.every(function (x) {
      return x < 10;
    });
    console.log(arr2); //true
    var arr3 = arr.every(function (x) {
      return x < 3;
    });
    console.log(arr3); // false

    // 14.some():判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true。
    var arr = [1, 2, 3, 4, 5];
    var arr2 = arr.some(function (x) {
      return x < 3;
    });
    console.log(arr2); //true
    var arr3 = arr.some(function (x) {
      return x < 1;
    });
    console.log(arr3); // false

    // 15.reduce()和 reduceRight()
    // 这两个方法都会实现迭代数组的所有项,然后构建一个最终返回的值。reduce()方法从数组
    // 的第一项开始,逐个遍历到最后。而 reduceRight()则从数组的最后一项开始,向前遍历到第一项。
    // 这两个方法都接收两个参数:一个在每一项上调用的函数和(可选的)作为归并基础的初始值。
    // 传给 reduce()和 reduceRight()的函数接收 4 个参数:前一个值、当前值、项的索引和数组对象。
    // 这个函数返回的任何值都会作为第一个参数自动传给下一项。第一次迭代发生在数组的第二项上,因此
    // 第一个参数是数组的第一项,第二个参数就是数组的第二项。
    // 下面代码用reduce()实现数组求和,数组一开始加了一个初始值10。
    var values = [1, 2, 3, 4, 5];
    var sum = values.reduceRight(function (prev, cur, index, array) {
      return prev + cur;
    }, 10);
    console.log(sum); //25  1+2+3+4+5+10=25

    // 16.数组拷贝
    //方法1
    var a = [1, 2, 3];
    var b = a.slice();
    a.reverse;
    console.log(a); //[3,2,1]
    console.log(b); //[1,2,3]
    //方法2
    var c = [4, 5, 6];
    var d = c.concat();
    c.reverse();
    console.log(c); //[6,5,4]
    console.log(d); //[4,5,6]

    // 17.数组相等
    // 先说下坑吧: 
    // 任意两个数组相等都会返回false;[]=[];//false 
    // 怎么办?千万不要逐项去比较,看看上面可用的方法:toString(); 
    // 转化为字符串一次就比较完了。

Related articles:

Array operation examples in JS

How to create such an array

Related videos:

Creation and operation of arrays in JavaScript-javascript elementary video tutorial

The above is the detailed content of Detailed explanation of the method of creating arrays in js that must be mastered (pure code). 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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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