search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript Array object_javascript skills

本文介紹了Js的Array 陣列對象,具體內容如下

目錄
1. 介紹:介紹 Array 陣列物件的說明、定義方式、屬性。

2. 實例方法:介紹 Array 物件的實例方法:concat、every、filter、forEach、indexOf、join、lastIndexOf、map、pop、push、reverse、shift、slice、sort、splice、toString、tounshift等。

3. 靜態方法:介紹 Array 物件的靜態方法:Array.isArray()。

4. 實際操作:對 Array 進行範例操作:索引、for遍歷、淺度複製、深度複製等操作。

 一. 介紹
1.1 說明

      陣列是數值的有序集合。每個值叫做一個元素,而每個元素在陣列中都有一個位置,以數字表示,稱為索引。 JavaScript陣列是無型別:陣列元素可以是任意型別,而且同一個陣列中的不同元素也可能有不同的型別。 --《JavaScript權威指南(第六版)》 

1.2 定義方式

var names = new Array("张三", "李四", "王五");
//或者
var names = ["张三", "李四", "王五"];

1.3 屬性

length:表示陣列內的元素長度。

二. 實例方法
常用方法:

1) unshift() :在陣列頭部插入元素

2) shift() :移除並傳回陣列的第一個元素

3) push() :在陣列尾部插入元素

4) pop() :移除並傳回陣列的最後一個元素

2.1 concat() :把元素銜接到陣列中。不會修改原先的array,傳回新的陣列

參數:

①value1,value2.....valueN :任多個值

傳回值:

{Array} 一個新的數組,包含原先的Array和新加入的元素。

範例:

var demoArray = ['a', 'b', 'c'];
var demoArray2 = demoArray.concat('e');
console.log(demoArray); // => demoArray:['a','b','c'] 原数组不发生变更
console.log(demoArray2); // => ['a','b','c','e']

2.2 every() :依序遍歷元素,判斷每個元素是否都為true

參數:

①function(value,index,self){} :每個元素都會使用此函數判斷是否為true,當判斷到一個為false時,立即結束遍歷。

  value :陣列遍歷的元素

  index :元素序號

  self :Array本身

傳回值:

{Boolean} :只有每個元素都為true才回傳true;只要一個為false,就回傳false。

範例:

var demoArray = [1, 2, 3];
var rs = demoArray.every(function (value, index, self) {
 return value > 0;
});
console.log(rs); // => true
 

2.3 filter() :依序遍歷元素,傳回包含符合條件元素的新的陣列

參數:

①function(value,index,self){} :每個元素依序呼叫此函數,傳回包含符合條件元素的新的陣列。

  value :陣列遍歷的元素

  index :元素序號

  self :Array本身

傳回值:

{Array} 一個包含符合條件元素的新的陣列

範例:

var demoArray = [1, 2, 3];
var rs = demoArray.filter(function (value, index, self) {
 return value > 0;
});
console.log(rs); // => [1, 2, 3]

2.4 forEach() :依序遍歷元素,執行指定的函數;無回傳值

參數:

①function(value,index,self){} :每個元素依序呼叫此函數

  value :陣列遍歷的元素

  index :元素序號

  self :Array本身

傳回值:無

範例:

var demoArray = [1, 2, 3];
demoArray.forEach(function (value, index, self) {
 console.log(value); // => 依次输出:1 2 3
});

2.5 indexOf() :在陣列中尋找匹配元素。若不存在符合的元素時,就回傳-1。尋找的時候使用"==="運算符,所以要區分1和'1'

參數:

①value :要在陣列中尋找的值。

②start :開始尋找的序號位置,如果省略,則為0.

傳回值:

{Int} :傳回數組中第一個符合value的序號,若不存在,則回傳-1

範例:

['a', 'b', 'c'].indexOf('a'); // =>0
['a', 'b', 'c'].indexOf('a', 1); // =>-1
['a', 'b', 'c'].indexOf('d'); // =>-1
[1, 2, 3].indexOf('1'); // => -1 :采用的'==='匹配方式

2.6 join() :將陣列中所有元素透過一個分隔符號拼接為一個字串

參數:

①sparator {String}:各元素之間的分隔符,如果省略,預設以因為英文逗號','分隔。

傳回值:

{String} :各元素以sparator為分隔符,拼接而成的一個字串。

範例:

['a', 'b', 'c'].join(); // => 'a,b,c'
['a', 'b', 'c'].join('-'); // => 'a-b-c'

2.7 lastIndexOf :在陣列中反向尋找符合元素。若不存在符合的元素時,就回傳-1。尋找的時候使用"==="運算符,所以要區分1和'1'

參數:

①value :要在陣列中尋找的值。

②start :開始尋找的序號位置,如果省略,則從最後一個元素開始尋找。

傳回值:

{Int} :從右到左開始找出數組中第一個符合value的序號,若不存在,回傳-1

範例:

['a', 'b', 'c'].lastIndexOf('a'); // => 0
['a', 'b', 'c'].lastIndexOf('a', 1); // => 0
['a', 'b', 'c'].lastIndexOf('d'); // => -1
[1, 2, 3].lastIndexOf('1'); // => -1 :采用的'==='匹配方式
 

2.8 map() :依次遍历并计算每个元素,返回计算好的元素的数组

参数:

①function(value,index,self){} :每个元素依次调用此函数,返回计算好的元素

  value :数组遍历的元素

  index :元素序号

  self :Array本身

返回值:

{Array} 一个包含就算好的元素的新的数组

示例:

[1, 2, 3].map(function (value, index, self) {
 return value * 2;
}); // => [2, 4, 6]
 

2.9 pop() :移除并返回数组的最后一个元素

参数:无

返回值:

{Object} 数组的最后一个元素;若数组为空,返回undefined

示例:

var demoArray = ['a', 'b', 'c'];
demoArray.pop(); // => c
demoArray.pop(); // => b
demoArray.pop(); // => a
demoArray.pop(); // => undefined

2.10 push() :把元素添加到数组尾部

参数:

①value1,value2.....valueN :任意多个值添加到数组尾部

返回值:

{int} 数组新的长度

示例:

var demoArray = ['a', 'b', 'c'];
demoArray.push('d'); // => 4, demoArray : ['a', 'b', 'c', 'd']
demoArray.push('e', 'f'); // => 6, demoArray :['a', 'b', 'c', 'd', 'e', 'f']
console.log(demoArray); // => ['a', 'b', 'c', 'd', 'e', 'f']

2.11 reverse() :反转数组元素的顺序

参数:无

返回值:无(在原数组内进行元素顺序反转)。

示例:

var demoArray = ['a', 'b', 'c', 'd', 'e'];
demoArray.reverse();
console.log(demoArray); // => ["e", "d", "c", "b", "a"]

2.12 shift() :移除并返回数组的第一个元素

参数:无

返回值:

{Object} 数组的第一个元素;若数组为空,返回undefined。

示例:

var demoArray = ['a', 'b', 'c'];
demoArray.shift(); // => a
demoArray.shift(); // => b
demoArray.shift(); // => c
demoArray.shift(); // => undefined

2.13 slice(startIndex,endIndex) :返回数组的一部分

参数:

①startIndex :开始处的序号;若为负数,表示从尾部开始计算,-1代表最后一个元素,-2倒数第二个,依此类推。

②endIndex : 结束处的元素后一个序号,没指定就是结尾。截取的元素不包含此处序号的元素,结尾为此处序号的前一个元素。

返回值:

{Array} 一个新的数组,包含从startIndex到endIndex前一个元素的所有元素。

示例:

[1, 2, 3, 4, 5, 6].slice(); // => [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6].slice(1); // => [2, 3, 4, 5, 6] :从序号1开始截取
[1, 2, 3, 4, 5, 6].slice(0, 4); // => [1, 2, 3, 4] :截取序号0到序号3(序号4的前一个)的元素
[1, 2, 3, 4, 5, 6].slice(-2); // => [5, 6] :截取后面的2个元素
 

2.14 sort(opt_orderFunc) :按一定的规则进行排序

参数:

①opt_orderFunc(v1,v2) {Function}:可选的排序规则函数。若省略,将按照元素的字母进行从小到大排序。

  v1 :遍历时前面的元素。

  v2 :遍历时后面的元素。

排序规则:

比较v1和v2,返回一个数字来表示v1和v2的排序规则:

小于0 :v1小于v2,v1排在v2的前面。

等于0 :v1等于v2,v1排在v2的前面。

大于0 :v1大于v2,v1排在v2的后面。

返回值:无(在原先数组里进行排序操作)。

示例:

[1, 3, 5, 2, 4, 11, 22].sort(); // => [1, 11, 2, 22, 3, 4, 5] :这里都元素都被转换为字符,11的字符在2前
 
[1, 3, 5, 2, 4, 11, 22].sort(function (v1, v2) {
 return v1 - v2;
}); // => [1, 2, 3, 4, 5, 11, 22] :从小到大排序
 
[1, 3, 5, 2, 4, 11, 22].sort(function (v1, v2) {
 return -(v1 - v2); //取反,就可以转换为 从大到小
}); // => [22, 11, 5, 4, 3, 2, 1]
 

2.15 splice() :插入、删除数组元素

参数:

①start {int} :开始插入、删除或替换的起始序号。

②deleteCount {int} :要删除元素的个数,从start处开始计算。

③value1,value2 ... valueN {Object} :可选参数,表示要插入的元素,从start处开始插入。若②参不为0,那么先执行删除操作,再执行插入操作。

返回值:

{Array}  返回一个包含删除元素的新的数组。若②参为0,表示没元素删除,返回一个空数组。

示例:

// 1.删除
var demoArray = ['a', 'b', 'c', 'd', 'e'];
var demoArray2 = demoArray.splice(0, 2); // 删除从序号从0开始的2个元素,返回包含删除元素的数组:['a', 'b']
console.log(demoArray2); // => ['a', 'b']
console.log(demoArray); // => ['c', 'd', 'e']
 
// 2.插入
var demoArray = ['a', 'b', 'c', 'd', 'e'];
var demoArray2 = demoArray.splice(0, 0, '1', '2', '3'); // ②参为0,返回空数组
console.log(demoArray2); // => [ ]
console.log(demoArray); // => ['1', '2', '3', 'a', 'b', 'c', 'd', 'e']
 
// 3.先删除再插入
var demoArray = ['a', 'b', 'c', 'd', 'e'];
// 当②参不为0,那么先执行删除操作(删除序号从0开始的4个元素,返回包含被删除元素的数组),再执行插入操作
var demoArray2 = demoArray.splice(0, 4, '1', '2', '3');
console.log(demoArray2); // => ['a', 'b', 'c', 'd'] 
console.log(demoArray); // => ['1', '2', '3', 'a', 'b', 'c', 'd', 'e']
 

2.16 toString() :将数组中所有元素通过一个英文逗号','拼接为一个字符串

参数:无

返回值:

{String}  数组中所有元素通过一个英文逗号','拼接为一个字符串,并返回。与调用无参join()方法一样。

示例:

[1, 2, 3, 4, 5].toString(); // => '1,2,3,4,5'
['a', 'b', 'c', 'd', 'e'].toString(); // => 'a,b,c,d,e'

2.17 unshift() :在数组头部插入元素

参数:

①value1,value2.....valueN :任意多个值添加到数组头部

返回值:

{int} 数组新的长度

示例:

var demoArray = [];
demoArray.unshift('a'); // => demoArray:['a']
demoArray.unshift('b'); // => demoArray:['b', 'a']
demoArray.unshift('c'); // => demoArray:['c', 'b', 'a']
demoArray.unshift('d'); // => demoArray:['d', 'c', 'b', 'a']
demoArray.unshift('e'); // => demoArray:['e', 'd', 'c', 'b', 'a']

三. 静态方法
3.1 Array.isArray() :判断对象是否为数组

参数:

①value {Object}:任意对象

返回值:

{Boolean}  返回判断结果。当为 true时,表示对象为数组;为false时,表示对象不是数组

示例:

Array.isArray([]); // => true
Array.isArray(['a', 'b', 'c']); // => true
Array.isArray('a'); // => false
Array.isArray('[1, 2, 3]'); // => false

四. 实际操作
4.1 索引

说明:每个元素在数组中有一个位置,以数字表示,称为索引。索引是从0开始计,即第一个元素的索引为0,第二个元素的索引为1,依此类推;

        当获取一个数组不存在的索引时,返回 undefined。

示例:

var demoArray = ['a', 'b', 'c', 'd', 'e'];
demoArray[0]; // => 获取第一个元素:'a'
demoArray[0] = 1; // 设置第一个元素为 1
console.log(demoArray); // => demoArray:[1, 'b', 'c', 'd', 'e']
console.log(demoArray[9]); // => undefined :当获取的索引不存在时,返回 undefined

4.2 for 语句

说明:可以通过for语句逐个遍历数组

示例:

var demoArray = ['a', 'b', 'c', 'd', 'e'];
for (var i = 0, length = demoArray.length; i < length; i++) {
 console.log(demoArray[i]); // => 逐个输出数组内的元素
}

4.3 浅度复制

说明:Array类型是一种引用类型;当数组a复制给数组b时,对数组b进行元素修改,数组a也会发生修改。

示例:

var demoArrayA = ['a', 'b', 'c', 'd', 'e'];
var demoArrayB = demoArrayA; // 把数组A 赋值给数组B
demoArrayB[0] = 1; // 对数组B 的元素进行修改
console.log(demoArrayA); // => [1, 'b', 'c', 'd', 'e']:数组A 的元素也发生了变更
 

4.4 深度复制

说明:使用concat()方法,返回新的数组;防止浅度复制的情况发生,对数组b进行元素修改操作,数组a不发生变更。

示例:

var demoArrayA = ['a', 'b', 'c', 'd', 'e'];
var demoArrayB = demoArrayA.concat(); // 使用concat()方法,返回新的数组
demoArrayB[0] = 1; // 对数组B 的元素进行修改
console.log(demoArrayA); // => ['a', 'b', 'c', 'd', 'e']:数组A 的元素没变更
console.log(demoArrayB); // => [ 1, 'b', 'c', 'd', 'e']:数组B 的元素发生了变更

4.5 判断2个数组是否相等

说明:Array数组为引用类型,所以哪怕 []===[] 都会返回false,所以可通过数组toString()方法返回的字符串判断是否相等。

示例:

console.log([]===[]); // => false
console.log(['a', 'b'] === ['a', 'b']); // => false
console.log(['a', 'b'].toString() === ['a', 'b'].toString()); // true

以上就是本文的全部内容,希望对大家学习javascript  Array对象有所帮助。

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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)