search
HomeWeb Front-endJS TutorialIntroduction to basic and advanced JavaScript arrays

Introduction to basic and advanced JavaScript arrays

Sep 05, 2017 am 09:37 AM
javascriptjsRelated

The following editor will bring you a summary of basic and advanced JavaScript array methods (recommended). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Summary of common array methods:

Below I only summarize the commonly used array methods in es3. A total of There are 11 of them. The 9 new array methods in es5 will be summarized separately later.

1 method to connect arrays: concat()

2 methods to convert arrays into strings: join(), toString()

6 additions and deletions of array elements Methods: pop(), push(), shift(), unshift(), slice(), splice()

2 array sorting methods: reverse(), sort()

Method to connect arrays:

1. concat()

Function: connection Two arrays, merged into a new array.

Usage: arr1.concat(arr2, arr2...)

Example:


##

<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

var arr2 = new Array(3)

arr2[0] = "James"

arr2[1] = "Adrew"

arr2[2] = "Martin"

document.write(arr.concat(arr2))

</script>

Output:

George,John,Thomas,James,Adrew,Martin


Method to convert array to string:

1. join()

Function: Used to put all the elements in the array into a string. and separated by the specified delimiter.

Usage: arrayObject.join(separator)

Example:

##

<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

document.write(arr.join("."))

</script>

Output:

George.John. Thomas

Note: The return value is a string. If there is no separator, the default is comma separation.

2. toString()Function: Convert the array to a string and return the result.

Usage: arrayObject.toString()

Example:

##
<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George";

arr[1] = "John";

arr[2] = "Thomas";

document.write(arr.toString());

</script>

Output:

George,John,Thomas

The return value is the same as the string returned by the join() method without parameters. Elements in the array are separated by commas.

Methods to add and delete array elements:

##1. pop()

Function: Used to delete and return the last element of the array. Usage: arrayObject.pop()

The pop() method will delete the last element of arrayObject, decrement the array length by 1, and return the value of the element it deletes. If the array is already empty, pop() does not modify the array and returns an undefined value.

Example:

<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

document.write(arr)

document.write("<br />")

document.write(arr.pop())

document.write("<br />")

document.write(arr)

</script>

Output:


George,John,Thomas
Thomas
George,John


2, push()

Function: You can add one or more elements to the end of the array and return the new length. Usage: arrayObject.push(newelement1,newelement2,....,newelementX)

It directly modifies arrayObject instead of creating a new array. The push() method and pop() method use the first-in-last-pop function provided by the array.

Example:

<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

document.write(arr + "<br />")

document.write(arr.push("James") + "<br />")

document.write(arr)

</script>

Output:


George,John,Thomas
4
George,John,Thomas,James


3, shift()

Function: Used to delete the first element of the array and return the value of the first element. Usage: arrayObject.shift()

If the array is empty, the shift() method will do nothing and return an undefined value. Please note that this method does not create a new array, but directly modifies the original arrayObject.

Example:

<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

document.write(arr + "<br />")

document.write(arr.shift() + "<br />")

document.write(arr)

</script>

Output:


George,John,Thomas
George
John,Thomas


4, unshift()

Function: Adds one or more elements to the beginning of the array and returns the new length. Usage: arrayObject.unshift(newelement1,newelement2,....,newelementX)

The unshift() method will insert its parameters into the head of arrayObject and replace the existing elements Move sequentially to higher subscripts to make space. The first argument to the method will become the new element 0 of the array, if there is a second argument it will become the new element 1, and so on.

Please note that the unshift() method does not create a new creation, but directly modifies the original array. The unshift() method does not work correctly in Internet Explorer!

Example:

<script type="text/javascript">

var arr = new Array()

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

document.write(arr + "<br />")

document.write(arr.unshift("William") + "<br />")

document.write(arr)

</script>

Output:


##

George,John,Thomas
4
William,George,John,Thomas

5, slice()

Function: Returns selected elements from an existing array. Usage: arrayObject.slice(start,end)

##start

Required. Specifies where to start the selection. If negative, it specifies the position from the end of the array. That is, -1 refers to the last element, -2 refers to the second to last element, and so on.

end

可选。规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。

返回一个新的数组,包含从 start 到 end (不包括该元素)的 arrayObject 中的元素。

该方法并不会修改数组,而是返回一个子数组。如果想删除数组中的一段元素,应该使用方法 Array.splice()。


<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"

arr[1] = "John"

arr[2] = "Thomas"

document.write(arr + "<br />")

document.write(arr.slice(1) + "<br />")

document.write(arr)

</script>

输出:


George,John,Thomas
John,Thomas
George,John,Thomas

6,splice()

作用:向/从数组中添加/删除项目,然后返回被删除的项目。

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

index

必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。

howmany

必需。要删除的项目数量。如果设置为 0,则不会删除项目。

item1, ..., itemX

可选。向数组添加的新项目。

该方法会改变原始数组。

示例:


<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"
document.write(arr + "<br />")arr.splice(2,0,"William")
document.write(arr + "<br />")

</script>

输出:


George,John,Thomas,James,Adrew,Martin

George,John,William,Thomas,James,Adrew,Martin

数组元素排序:

1、reverse()

作用:用于颠倒数组中元素的顺序。

用法:arrayObject.reverse()

该方法会改变原来的数组,而不会创建新的数组。

示例:


<script type="text/javascript">

var arr = new Array(3)

arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"

document.write(arr + "<br />")

document.write(arr.reverse())

</script>

输出:


George,John,Thomas
Thomas,John,George

2,sort()

作用:用于对数组的元素进行排序。

用法:arrayObject.sort(sortby)

Sortby:可选,按规定是顺序排序。必须是函数。

相对于其他方法来说复杂了一点。

如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。

如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:

若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。

若 a 等于 b,则返回 0。

若 a 大于 b,则返回一个大于 0 的值。


<script type="text/javascript">

function sortNumber(a,b)
{
return a - b
}

var arr = new Array(6)

arr[0] = "10"

arr[1] = "5"

arr[2] = "40"

arr[3] = "25"

arr[4] = "1000"

arr[5] = "1"

document.write(arr + "<br />")

document.write(arr.sort(sortNumber))

</script>

输出:


10,5,40,25,1000,1
1,5,10,25,40,1000

上面这个例子是让数组元素从小到大排序,如果想实现从大到小排序,只需要将sortNumber函数中的a-b改为b-a即可。


<script type="text/javascript">

function sortNumber(a,b)

{

return b - a;

}

var arr = new Array(6)

arr[0] = "10"

arr[1] = "5"

arr[2] = "40"

arr[3] = "25"

arr[4] = "1000"

arr[5] = "1"

document.write(arr + "<br />")

document.write(arr.sort(sortNumber))

</script>

输出:


10,5,40,25,1000,1
1000,40,25,10,5,1

补充:

数组对象的属性:

属性

描述

constructor

返回对创建此对象的数组函数的引用。

length

设置或返回数组中元素的数目。

prototype

使您有能力向对象添加属性和方法。

以下这个例子展示了如何使用constructor属性


<script type="text/javascript">

var test=new Array();

if (test.constructor==Array)

{

document.write("This is an Array");

}

if (test.constructor==Boolean)

{

document.write("This is a Boolean");

}

if (test.constructor==Date)

{

document.write("This is a Date");

}

if (test.constructor==String)

{

document.write("This is a String");

}

</script>

输出:


This is an Array

length 属性可设置或返回数组中元素的数目。数组的 length 属性总是比数组中定义的最后一个元素的下标大 1。对于那些具有连续元素,而且以元素 0 开始的常规数组而言,属性 length 声明了数组中的元素的个数。设置 length 属性可改变数组的大小。如果设置的值比其当前值小,数组将被截断,其尾部的元素将丢失。如果设置的值比它的当前值大,数组将增大,新的元素被添加到数组的尾部,它们的值为 undefined。

获取数组的长度:arrayObject.length

The above is the detailed content of Introduction to basic and advanced JavaScript arrays. 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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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