Table of Contents
Declare arrays
1. Conventional method
2. Concise method
3. Literal
Array object method
1. forEach
2. map
3. concat
4. push
5. unshift
6. pop
7. shift
8. splice
9 The .slice
10. join
11. The every
12. The filter
13. The indexOf
14. reduce
15. reverse
16. sort
17. toString
18. at
19. find
20. some
Home Web Front-end JS Tutorial Summary of 20 common JavaScript array operations

Summary of 20 common JavaScript array operations

Apr 20, 2023 pm 03:43 PM
front end

ArrayObject in JavaScript, like arrays in other programming languages, is a collection of data. In JavaScript, the data inside an array can be of different types and has methods for performing common operations on arrays.

Declare arrays

There are three different declaration methods

1. Conventional method

const hobbys = new Array()
hobbys[0] = 'Basketball'
hobbys[1] = 'Badminton'
hobbys[2] = 'swimming'
console.log(hobbys)
// [ 'Basketball', 'Badminton', 'swimming' ]
Copy after login

2. Concise method

const hobbys = new Array('Basketball', 'Badminton','swimming')
console.log(hobbys)
// [ 'Basketball', 'Badminton', 'swimming' ]
Copy after login

3. Literal

const hobbys = ['Basketball','Badminton','swimming']
console.log(hobbys)
// [ 'Basketball', 'Badminton', 'swimming' ]
Copy after login

Array object method

1. forEach

forEach() method is used to call each element of the array and pass the element to the callback function. There is no return value, which is essentially equivalent to a for loop that executes the function function on each item. The original array will not be changed.

// currentValue:必需,当前元素 index:可选,当前元素的索引值 arr:可选,当前元素所属的数组对象。
array.forEach(function(currentValue, index, arr))
Copy after login
let array = ['a', 'b', 'c']
let func = (currentValue, index, arr) => {
  currentValue += 's'  
  console.log('currentValue:' + currentValue + ' index:' + index + ' arr:' + arr)
}
array.forEach(func)
console.log(array)

// 控制台输出:
// currentValue:as index:0 arr:a,b,c
// currentValue:bs index:1 arr:a,b,c
// currentValue:cs index:2 arr:a,b,c
// [ 'a', 'b', 'c' ]
Copy after login

2. map

Processes each element of the array through the specified function and returns the processed array.

The map() method returns a new array, and the elements in the array are the values ​​of the original array elements after calling the function. The method processes elements sequentially in the original array element order. The original array will not be changed.

// currentValue:必须,当前元素的值  index:可选,当前元素的索引值 arr:可选,当前元素属于的数组对象
array.map(function(currentValue,index,arr))
Copy after login
let array = [1, 2, 3, 4, 5]
let result = array.map((item) => { 
  return item += 5
})
console.log(array)
console.log(result)
// [ 1, 2, 3, 4, 5 ]
// [ 6, 7, 8, 9, 10 ]
Copy after login

3. concat

The concat() method in JavaScript is used to concatenate two or more arrays and return the result.

// array1, array2, ..., arrayN 必需,该参数可以是具体的值,也可以是数组对象,可以是任意多个
array1.concat(array2,array3,...,arrayN)
Copy after login
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
const array3 = array1.concat(array2)
console.log(array3)
const array4 = array1.concat('123')
console.log(array4)
// [ 'a', 'b', 'c', 'd', 'e', 'f' ]
// [ 'a', 'b', 'c', '123' ]
Copy after login

4. push

The push() method in Javascript array is used to add one or more elements to the end of the array, and Returns the new length.

let fruits = ["Banana", "Orange", "Apple", "Mango"]
let length = fruits.push("Kiwi")
console.log(fruits)
console.log(length)
// [ 'Banana', 'Orange', 'Apple', 'Mango', 'Kiwi' ]
// 5
Copy after login

5. unshift

The unshift() method adds one or more elements to the beginning of the array and returns the new length.

let fruits = ["Banana", "Orange", "Apple", "Mango"]
let length = fruits.unshift("Lemon", "Pineapple")
console.log(fruits)
console.log(length)
// [ 'Lemon', 'Pineapple', 'Banana', 'Orange', 'Apple', 'Mango' ]
// 6
Copy after login

6. pop

The pop() method is used to delete the last element of the array and return the deleted element.

let sites = ['Google', 'Runoob', 'Taobao', 'Zhihu', 'Baidu']
let result = sites.pop()
console.log(sites)
console.log(result)
// [ 'Google', 'Runoob', 'Taobao', 'Zhihu' ]
// Baidu
Copy after login

7. shift

The shift() method is used to delete the first element of the array and return the value of the first element

let fruits = ["Banana", "Orange", "Apple", "Mango"];
let result = fruits.shift()
console.log(fruits)
console.log(result)
// [ 'Orange', 'Apple', 'Mango' ]
// Banana
Copy after login

8. splice

splice() method is used to add or delete elements in the array and return the deleted element array

// 参数 Values: index: 必需,规定从何处添加/删除元素
// howmany: 可选,规定应该删除多少元素 必须是数字,但可以是 "0"
// item1, ..., itemX 可选,要添加到数组的新元素
array.splice(index,howmany,item1,.....,itemX)
Copy after login
let fruits = ["Banana", "Orange", "Apple", "Mango"]
let result = fruits.splice(1, 2, "Lemon", "Kiwi")
console.log(fruits)
console.log(result)
// [ 'Banana', 'Lemon', 'Kiwi', 'Mango' ]
// [ 'Orange', 'Apple' ]
Copy after login

9 The .slice

slice() method returns selected elements from an existing array. You can also extract a portion of a string and return the extracted portion as a new string. The original array will not be changed.

// start: 可选,规定从何处开始选取 若为负值,表示从原数组中的倒数第几个元素开始提取
// end: 可选,规定从何处结束选取 如果没有指定该参数,那么切分的数组包含从start到数组结束的所有元素
array.slice(start, end)
Copy after login
let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]
let result1 = fruits.slice(1, 3)
let result2 = fruits.slice(2)
console.log(fruits)
console.log(result1)
console.log(result2)
// [ 'Banana', 'Orange', 'Lemon', 'Apple', 'Mango' ]
// [ 'Orange', 'Lemon' ]
// [ 'Lemon', 'Apple', 'Mango' ]
Copy after login

10. join

join() method combines all array elements into a string. It behaves like toString(), but you can also specify the delimiter

// separator: 可选,指定要使用的分隔符 如果省略该参数,则使用逗号作为分隔符
array.join(separator)
Copy after login
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let energy1 = fruits.join();
let energy2 = fruits.join('-');
console.log(energy1)
console.log(energy2)
// Banana,Orange,Apple,Mango
// Banana-Orange-Apple-Mango
Copy after login

11. The every

every() method is used to detect whether all elements of the array match Specify the condition (provided through the function).

array.every(function(currentValue,index,arr))
Copy after login
let ages = [32, 33, 16, 40]
let nums = [32, 33, 19, 40]
function checkAdult(age) {
  return age >= 18
}
function checkNums(num) {
  return num >= 18
}
// 16不满足大于18,故结果false
let result1 = ages.every(checkAdult)
// 每一项都满足条件,故结果true
let result2 = nums.every(checkNums)
console.log(result1)
console.log(result2)
// false
// true
Copy after login

12. The filter

filter() method creates a new array. The elements in the new array are checked for all elements in the specified array that meet the conditions. The original array will not be changed.

array.filter(function(currentValue,index,arr), thisValue)
Copy after login
let ages = [32, 33, 16, 40];
function checkAdult(age) {
  return age >= 18;
}
let result = ages.filter(checkAdult)
console.log(result)
// [ 32, 33, 40 ]
Copy after login

13. The indexOf

indexOf() method returns the position where a specified string value first appears in the string. If not found, -1

// searchvalue: 必需。规定需检索的字符串值。
// start: 可选的整数参数。规定在字符串中开始检索的位置。值:0~array.length-1
string.indexOf(searchvalue,start)
Copy after login
let str = "Hello world, welcome to the universe.";
// 输出w所在的下标索引13(空格也算),没有找到会返回-1
let n = str.indexOf("welcome");
console.log(n)
console.log(str[n])
// 13
// w
Copy after login

14. reduce

reduce() method receives a function as an accumulator, each value in the array (from left to right ) begins to reduce and is finally calculated to a value.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy after login
let numbers = [2, 3, 5, 6]
function getSum(total, num) {
  return total + num
}
let result = numbers.reduce(getSum, 0)
console.log(result)
// 16
Copy after login

15. reverse

reverse() method is used to reverse the order of elements in the array. Will change the original array and return the array in changed order.

let fruits = ["Banana", "Orange", "Apple", "Mango"]
let resut = fruits.reverse()
console.log(fruits)
console.log(resut)
// [ 'Mango', 'Apple', 'Orange', 'Banana' ]
// [ 'Mango', 'Apple', 'Orange', 'Banana' ]
Copy after login

16. sort

sort() method is used to sort the elements of the array. The sort order can be alphabetical or numerical, and in ascending or descending order.

// sortfunction: 可选。规定排序顺序。必须是函数。
array.sort(sortfunction)
Copy after login
let fruits = ["Banana", "Orange", "Apple", "Mango"]
let ages = [9, 3, 4, 5, 7, 10]
// 升序
let agesFunAsc = function (ag1,ag2) {
  return ag1 - ag2
}
// 降序
let agesFunDes= function (ag1,ag2) {
  return -(ag1 - ag2)
}
fruits.sort()
ages.sort(agesFunAsc)
console.log(fruits)
console.log(ages)
ages.sort(agesFunDes)
console.log(ages)
// [ 'Apple', 'Banana', 'Mango', 'Orange' ]
// [ 3, 4, 5, 7, 9, 10 ]
// [ 10, 9, 7, 5, 4, 3 ]
Copy after login

17. toString

toString() method is used to convert numbers to strings.

number.toString(radix)
Copy after login
let num = 15
let n = num.toString()
// 也可以使用不同的进制把一个数字转换为字符串
// 2进制
let b = num.toString(2);
// 8进制
let c = num.toString(8);
// 16进制
let d = num.toString(16);
console.log(n)
console.log(b)
console.log(c)
console.log(d)
// 15
// 1111
// 17
// f
Copy after login

18. at

at() method accepts an integer value and returns the value of the at index, both positive and negative integers are acceptable. A negative integer means counting down from the last item in the array.

array.at(index)
Copy after login
let str = 'helso word'
let item1 = str.at(2)
let item2 = str.at(-1)
console.log(item1)
console.log(item2)
// l
// d
Copy after login

19. find

find() method returns the value of the first element of the array that passes the test (judged within the function).

array.find(function(currentValue, index, arr),thisValue)
Copy after login
let ages = [3, 10, 18, 20];
function checkAdult(age) {
  return age >= 18;
}
let value = ages.find(checkAdult)
console.log(value)
// 18
Copy after login

20. some

some() method is used to detect whether the elements in the array meet the specified conditions (provided by the function).

array.some(function(currentValue,index,arr),thisValue)
Copy after login
rrree

The above is the detailed content of Summary of 20 common JavaScript array operations. 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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

How to solve cross-domain issues? A brief analysis of common solutions How to solve cross-domain issues? A brief analysis of common solutions Apr 25, 2023 pm 07:57 PM

Cross-domain is a scenario often encountered in development, and it is also an issue often discussed in interviews. Mastering common cross-domain solutions and the principles behind them can not only improve our development efficiency, but also perform better in interviews.

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

How to use Go language for front-end development? How to use Go language for front-end development? Jun 10, 2023 pm 05:00 PM

With the development of Internet technology, front-end development has become increasingly important. Especially the popularity of mobile devices requires front-end development technology that is efficient, stable, safe and easy to maintain. As a rapidly developing programming language, Go language has been used by more and more developers. So, is it feasible to use Go language for front-end development? Next, this article will explain in detail how to use Go language for front-end development. Let’s first take a look at why Go language is used for front-end development. Many people think that Go language is a

See all articles