Home Web Front-end JS Tutorial Detailed explanation of Js Array array object_javascript skills

Detailed explanation of Js Array array object_javascript skills

May 16, 2016 pm 03:14 PM
js

This article shares relevant information about the Array array object of Js for your reference. The specific content is as follows

1. Introduction
1.1 Description
An array is an ordered collection of values. Each value is called an element, and each element has a position in the array, represented by a number, called an index. JavaScript arrays are untyped: array elements can be of any type, and different elements in the same array may have different types. --"The Definitive Guide to JavaScript (6th Edition)"

1.2 Definition

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

Copy after login

1.3 Properties

length: Indicates the length of the elements in the array.

2. Instance method
Common methods:

1) unshift(): Insert elements at the head of the array

2) shift(): Remove and return the first element of the array

3) push(): Insert elements at the end of the array

4) pop(): Remove and return the last element of the array

2.1 concat(): Concatenate the elements into the array. The original array will not be modified and a new array will be returned

Parameters:

①value1,value2....valueN: any number of values

Return value:

{Array} A new array, containing the original Array and the newly added elements.

Example:

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

2.2 every(): Traverse the elements in sequence and determine whether each element is true

Parameters:

①function(value,index,self){}: Each element will use this function to determine whether it is true. When one is determined to be false, the traversal will end immediately.

Value: elements of array traversal

Index: element number

Self: Array itself

Return value:

{Boolean}: Returns true only if every element is true; returns false as long as one element is false.

Example:

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

2.3 filter(): Traverse the elements in sequence and return a new array containing elements that meet the conditions

Parameters:

①function(value,index,self){}: Call this function on each element in turn and return a new array containing elements that meet the conditions.

Value: elements of array traversal

Index: element number

Self: Array itself

Return value:

{Array} A new array containing elements that meet the criteria

Example:

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

2.4 forEach(): Traverse the elements in sequence and execute the specified function; no return value

Parameters:

①function(value,index,self){}: Each element calls this function in turn

Value: elements of array traversal

Index: element number

Self: Array itself

Return value: None

Example:

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

2.5 indexOf(): Find matching elements in the array. If there is no matching element, -1 is returned. Use the "===" operator when searching, so you need to distinguish between 1 and '1'

Parameters:

①value: The value to be found in the array.

②start: The serial number position to start searching. If omitted, it will be 0.

Return value:

{Int}: Returns the serial number of the first matching value in the array. If it does not exist, returns -1

Example:

['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 :采用的'==='匹配方式
Copy after login

2.6 join(): Splice all the elements in the array into a string through a separator

Parameters:

①sparator {String}: The separator between each element. If omitted, it will be separated by English commas ',' by default.

Return value:

{String}: Each element is spliced ​​into a string with sparator as the separator.

Example:

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

2.7 lastIndexOf: Find the matching element in reverse in the array. If there is no matching element, -1 is returned. Use the "===" operator when searching, so you need to distinguish between 1 and '1'

Parameters:

①value: The value to be found in the array.

②start: The serial number position to start searching. If omitted, the search will start from the last element.

Return value:

{Int}: Find the sequence number of the first matching value in the array from right to left. If it does not exist, return -1

Example:

['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 :采用的'==='匹配方式
Copy after login

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]
Copy after login

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

参数:无

返回值:

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

示例:

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

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']
Copy after login

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

参数:无

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

示例:

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

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

参数:无

返回值:

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

示例:

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

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个元素
Copy after login

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]
Copy after login

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']
 
Copy after login

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'
Copy after login

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']
 
Copy after login

3. 静态方法
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
Copy after login

4. 实际操作
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
Copy after login

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]); // => 逐个输出数组内的元素
}
Copy after login

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 的元素也发生了变更 
Copy after login

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 的元素发生了变更
Copy after login

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
Copy after login

以上就会说关于javascript Array对象的全部内容,希望大家喜欢。

Statement of this Website
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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles