Home Web Front-end H5 Tutorial What are the differences between JavaScript's methods for arrays?

What are the differences between JavaScript's methods for arrays?

Nov 18, 2017 pm 05:39 PM
javascript js Which

In JavaScript, there are many methods for adding, removing, and replacing array elements. Many methods can achieve the same function, but they are very different. Today we will compare them. In JavaScript What is the secret of the array method?

JavaScript provides a variety of methods for adding, removing, and replacing array elements, but some will affect the original array; some will not, and they will create a new array.

Note: Distinguish the difference between the following two methods:

array.splice() affects the original array

array.slice() does not affect the original array


I. New addition: affecting the original array

Using array.push() and array.ushift() to add new elements will affect the original array.

let mutatingAdd = ['a', 'b', 'c', 'd', 'e'];
mutatingAdd.push('f'); // ['a', 'b', 'c', 'd', 'e', 'f']
mutatingAdd.unshift('z'); // ['z', 'b', 'c', 'd', 'e' 'f']
Copy after login

II. New addition: does not affect the original array

There are two ways to add elements that will not affect the original array. The first is array.concat().

const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = arr1.concat('f'); // ['a', 'b', 'c', 'd', 'e', 'f']  (注:原文有误,我做了修改 “.” ---> “,”)
console.log(arr1); // ['a', 'b', 'c', 'd', 'e']
Copy after login

The second method is to use JavaScript's spread operator. The spread operator is three dots (...)

const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = [...arr1, 'f']; // ['a', 'b', 'c', 'd', 'e', 'f']  
const arr3 = ['z', ...arr1]; // ['z', 'a', 'b', 'c', 'd', 'e']
Copy after login

The spread operator will copy the original array, starting from the original array. All elements are taken out of the array and stored in the new environment.


III. Removal: Affects the original array

When array.pop() and array.shift() are used to remove array elements, the original array will be affected. array.

let mutatingRemove = ['a', 'b', 'c', 'd', 'e'];  
mutatingRemove.pop(); // ['a', 'b', 'c', 'd']  
mutatingRemove.shift(); // ['b', 'c', 'd']
Copy after login

array.pop() and array.shift() return the removed element, you can get the removed element through a variable.

let mutatingRemove = ['a', 'b', 'c', 'd', 'e'];
const returnedValue1 = mutatingRemove.pop();  
console.log(mutatingRemove); // ['a', 'b', 'c', 'd']  
console.log(returnedValue1); // 'e'
const returnedValue2 = mutatingRemove.shift();  
console.log(mutatingRemove); // ['b', 'c', 'd']  
console.log(returnedValue2); // 'a'
Copy after login

array.splice() can also delete elements of an array.

let mutatingRemove = ['a', 'b', 'c', 'd', 'e'];  
mutatingRemove.splice(0, 2); // ['c', 'd', 'e']
Copy after login

Like array.pop() and array.shift(), array.splice() also returns the removed elements.

let mutatingRemove = ['a', 'b', 'c', 'd', 'e'];  
let returnedItems = mutatingRemove.splice(0, 2);  
console.log(mutatingRemove); // ['c', 'd', 'e']  
console.log(returnedItems) // ['a', 'b']
Copy after login

IV. Removal: Does not affect the original array

JavaScript 的 array.filter() 方法基于原数组创建一个新数组,新数组仅包含匹配特定条件的元素。
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = arr1.filter(a => a !== 'e'); // ['a', 'b', 'c', 'd'](注:原文有误,我做了修改)  
// 或者
const arr2 = arr1.filter(a => {  
  return a !== 'e';
}); // ['a', 'b', 'c', 'd'](注:原文有误,我做了修改)
Copy after login

The condition of the above code is "not equal to 'e'", so the new array (arr2) does not contain 'e'.

The uniqueness of the arrow function:

Single-line arrow function, the 'return' keyword comes by default and does not need to be written manually.

However, multi-line arrow functions need to return a value explicitly.

Another way that does not affect the original array is array.slice() (not to be confused with array.splice()).

const arr1 = ['a', 'b', 'c', 'd', 'e'];  
const arr2 = arr1.slice(1, 5) // ['b', 'c', 'd', 'e']  
const arr3 = arr1.slice(2) // ['c', 'd', 'e']
Copy after login

V. Replacement: affecting the original array

If you know which element to replace, you can use array.splice().

let mutatingReplace = ['a', 'b', 'c', 'd', 'e'];  
mutatingReplace.splice(2, 1, 30); // ['a', 'b', 30, 'd', 'e']  
// 或者
mutatingReplace.splice(2, 1, 30, 31); // ['a', 'b', 30, 31, 'd', 'e']
Copy after login

VI. Replacement: Does not affect the original array

You can use array.map() to create a new array, and you can check each element and replace them according to specific conditions.

const arr1 = ['a', 'b', 'c', 'd', 'e']  
const arr2 = arr1.map(item => {  
  if(item === 'c') {
    item = 'CAT';
  }
  return item;
}); // ['a', 'b', 'CAT', 'd', 'e']
Copy after login

Use array.map() to convert data

array.map() is a powerful method that can be used to convert data without polluting the original data source.

const origArr = ['a', 'b', 'c', 'd', 'e'];  
const transformedArr = origArr.map(n => n + 'Hi!'); // ['aHi!', 'bHi!', 'cHi!', 'dHi!', 'eHi!']  
console.log(origArr); // ['a', 'b', 'c', 'd', 'e']; // 原数组毫发无损
Copy after login

There are so many method comparisons about arrays. I hope it can help everyone understand and use arrays in JS.


Related reading:

About JS array Array method summary

js array deduplication method Summary

Parsing the parameter passing method of angularjs array

The above is the detailed content of What are the differences between JavaScript's methods for arrays?. 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.

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

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

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

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

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

See all articles