Home Web Front-end JS Tutorial Summary of common array operation methods in JavaScript (code)

Summary of common array operation methods in JavaScript (code)

Apr 13, 2019 am 10:57 AM
javascript

What this article brings to you is a summary (code) of common array operation methods in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. concat()

The concat() method is used to connect two or more arrays. This method does not modify the existing array, it only returns a copy of the concatenated array.

var arr1 = [1,2,3];    
var arr2 = [4,5];    
var arr3 = arr1.concat(arr2);
console.log(arr1);//[1, 2, 3]
console.log(arr3);//[1, 2, 3, 4, 5]
Copy after login

2. join()

The join() method is used to put all elements in the array into a string. Elements are separated by the specified delimiter. By default, ',' is used to separate the elements, which does not change the original array.

var arr = [2,3,4];
console.log(arr.join());//2,3,4
console.log(arr);//[2, 3, 4]
Copy after login

3. push()

push() method can add one or more elements to the end of the array and return the new length. Adding at the end returns the length, which will change the original array.

var a = [2,3,4];    
var b = a.push(5);
console.log(a); //[2,3,4,5]
console.log(b);//4
push方法可以一次添加多个元素push(data1,data2....)
Copy after login

4. pop()

The pop() method is used to delete and return the last element of the array. Returning the last element will change the original array.

var arr = [2,3,4];
console.log(arr.pop());//4
console.log(arr); //[2,3]
Copy after login

5. shift()

The shift() method is used to delete the first element of the array and return the value of the first element. Returns the first element, changing the original array.

var arr = [2,3,4];
console.log(arr.shift()); //2
console.log(arr);  //[3,4]
Copy after login

6. unshift()

The unshift() method can add one or more elements to the beginning of the array and return the new length. Returns the new length, changing the original array.

var arr = [2,3,4,5];
console.log(arr.unshift(3,6)); //6
console.log(arr); //[3, 6, 2, 3, 4, 5]
Copy after login

7. slice()

Returns a new array containing the elements in arrayObject from start to end (excluding this element). Returns the selected element. This method does not modify the original array.

var arr = [2,3,4,5];
console.log(arr.slice(1,3));  //[3,4]
console.log(arr);  //[2,3,4,5]
Copy after login

8. splice()

The splice() method can delete zero or more elements starting from index and replace them with one or more values ​​declared in the parameter list elements that were removed. If an element is deleted from arrayObject, an array containing the deleted element is returned. The splice() method directly modifies the array.

var a = [5,6,7,8];
console.log(a.splice(1,0,9)); //[]
console.log(a);  // [5, 9, 6, 7, 8]    
var b = [5,6,7,8];
console.log(b.splice(1,2,3));  //[6, 7]
console.log(b); //[5, 3, 8]
Copy after login

9. substring() and substr()

Same point: if you just write one parameter:

substr(startIndex);

substring(startIndex);

Both have the same function: they intercept the string fragment from the current subscript to the end of the string.

var str = '123456789';
console.log(str.substr(2));    //  "3456789"
console.log(str.substring(2));//  "3456789"
Copy after login

Difference: The second parameter

substr(startIndex,lenth): The second parameter is to intercept the length of the string (intercept a string of a certain length from the starting point)

substring (startIndex, endIndex): The second parameter is to intercept the final subscript of the string (intercept the string between the two positions, 'including the head but not the tail')
console.log("123456789".substr(2,5));    //  "34567"
console.log("123456789".substring(2,5));//  "345"
Copy after login

10. sort Sorting
Sort by Unicode code position, default ascending order:

  • var fruit = ['cherries', 'apples', 'bananas'];
  • fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
Copy after login

11. reverse()
reverse() method is used to reverse the order of elements in the array. What is returned is the reversed array, which will change the original array.

var arr = [2,3,4];
console.log(arr.reverse()); //[4, 3, 2]
console.log(arr);  //[4, 3, 2]
Copy after login

Twelve, indexOf and lastIndexOf
both accept two parameters: the value to be searched and the starting position to search.
If it does not exist, return -1; if it exists, return the position. indexOf searches from front to back, and lastIndexOf searches from back to front.

indexOf:
var a = [2, 9, 9];
    a.indexOf(2); // 0
    a.indexOf(7); // -1
if (a.indexOf(7) === -1) {      
// element doesn't exist in array   
}

lastIndexOf:
var numbers = [2, 5, 9, 2];
    numbers.lastIndexOf(2);     // 3
    numbers.lastIndexOf(7);     // -1
    numbers.lastIndexOf(2, 3);  // 3
    numbers.lastIndexOf(2, 2);  // 0
    numbers.lastIndexOf(2, -2); // 0
    numbers.lastIndexOf(2, -1); // 3
Copy after login

13. every
Run the given function on each item of the array, and return true if each item returns ture.

function isBigEnough(element, index, array) {
      return element < 10;
}
[2, 5, 8, 3, 4].every(isBigEnough);   // true
Copy after login

14. some
Run the given function on each item of the array. If any item returns ture, it returns true.

function compare(element, index, array) {
      return element > 10;
}
[2, 5, 8, 1, 4].some(compare);  // false
[12, 5, 8, 1, 4].some(compare); // true
Copy after login

15. filter
Run the given function on each item of the array and return an array composed of items whose result is true.

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];    
var longWords = words.filter(function(word){
      return word.length > 6;
});
// Filtered array longWords is ["exuberant", "destruction", "present"]
Copy after login

16. map
Run the given function on each item of the array and return the result of each function call to form a new array.

var numbers = [1, 5, 10, 15];    
var doubles = numbers.map(function(x) {
       return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
Copy after login

17. forEach array traversal

const items = ['item1', 'item2', 'item3'];    
const copy = [];    
items.forEach(function(item){
    copy.push(item)
});
Copy after login

18. reduce
reduce executes the callback function for each element in the array in sequence, excluding those that are deleted or have never been deleted from the array The assigned element accepts four parameters: the initial value (or the return value of the last callback function), the current element value, the current index, and the array in which reduce is called.

无初始值:
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr, sum);
Copy after login
Print results:
1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10

You can see it here In the above example, the index starts from 1, and the value of the first prev is the first value of the array. The array length is 4, but the reduce function loops 3 times.
Has initial value:

var  arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
},0) //注意这里设置了初始值
console.log(arr, sum);
Copy after login
Print result:
0 1 0
1 2 1
3 3 2
6 4 3
[1, 2, 3 , 4] 10

In this example, the index starts from 0, the first prev value is the initial value 0 we set, the array length is 4, and the reduce function loops 4 times.
Conclusion: If no initialValue is provided, reduce will execute the callback method starting from index 1, skipping the first index. If initialValue is provided, starts at index 0.
ES6 adds new methods for operating arrays
1. find()
Pass in a callback function, find the first element in the array that meets the current search rules, return it, and terminate the search.

const arr = [1, "2", 3, 3, "2"]
console.log(arr.find(n => typeof n === "number")) // 1
Copy after login

2. findIndex()
Pass in a callback function, find the first element in the array that meets the current search rules, return its subscript, and terminate the search.

const arr = [1, "2", 3, 3, "2"]
console.log(arr.findIndex(n => typeof n === "number")) // 0
Copy after login

3. fill()
Replace the elements in the array with new elements, and you can specify the replacement subscript range.

arr.fill(value, start, end)
Copy after login

4、copyWithin()
选择数组的某个下标,从该位置开始复制数组元素,默认从0开始复制。也可以指定要复制的元素范围。

arr.copyWithin(target, start, end)
const arr = [1, 2, 3, 4, 5]
console.log(arr.copyWithin(3))
// [1,2,3,1,2] 从下标为3的元素开始,复制数组,所以4, 5被替换成1, 2
const arr1 = [1, 2, 3, 4, 5]
console.log(arr1.copyWithin(3, 1))
// [1,2,3,2,3] 从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,所以4, 5被替换成2, 3
const arr2 = [1, 2, 3, 4, 5]
console.log(arr2.copyWithin(3, 1, 2))
// [1,2,3,2,5] 从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,结束位置为2,所以4被替换成2
Copy after login

5、from
将类似数组的对象(array-like object)和可遍历(iterable)的对象转为真正的数组。

const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]
Array.from('foo');
// ["f", "o", "o"]
Copy after login

6、of
用于将一组值,转换为数组。这个方法的主要目的,是弥补数组构造函数 Array() 的不足。因为参数个数的不同,会导致 Array() 的行为有差异。

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8)// [3, 11, 8]
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Array(7);// [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]
Copy after login

7、entries() 返回迭代器:返回键值对

//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.entries()) {
      console.log(v)
}
// [0, 'a'] [1, 'b'] [2, 'c']

//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.entries()) {
      console.log(v)
}
// ['a', 'a'] ['b', 'b'] ['c', 'c']

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.entries()) {
      console.log(v)
}
// ['a', 'a'] ['b', 'b']
Copy after login

8、values() 返回迭代器:返回键值对的value

//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.values()) {
      console.log(v)
}
//'a' 'b' 'c'

//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.values()) {
      console.log(v)
}
// 'a' 'b' 'c'

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.values()) {
      console.log(v)    
}
// 'a' 'b'
Copy after login

9、keys() 返回迭代器:返回键值对的key

//数组
const arr = ['a', 'b', 'c'];    
for(let v of arr.keys()) {
      console.log(v)
}
// 0 1 2

//Set
const arr = new Set(['a', 'b', 'c']);    
for(let v of arr.keys()) {
      console.log(v)
}
// 'a' 'b' 'c'

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.keys()) {
      console.log(v)
}
// 'a' 'b'
Copy after login

10、includes
判断数组中是否存在该元素,参数:查找的值、起始位置,可以替换 ES5 时代的 indexOf 判断方式。indexOf 判断元素是否为 NaN,会判断错误。

var a = [1, 2, 3];
    a.includes(2); // true
    a.includes(4); // false
Copy after login

【相关推荐:JavaScript视频教程

The above is the detailed content of Summary of common array operation methods in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles