search
HomeWeb Front-endFront-end Q&AHow to delete elements in an array in es6

How to delete elements in an array in es6

May 19, 2022 pm 07:17 PM
es6es6 array

Deletion method: 1. Use shift() to delete the first element, the syntax "arr.shift()"; 2. Use pop() to delete the last element, the syntax "arr.pop()"; 3. Use splice() to delete any element based on the subscript, the syntax is "arr.splice (start subscript, delete the number of elements)".

How to delete elements in an array in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In JavaScript, there are many ways to delete array elements. Here are some of them.

Method 1: Use the shift() function to delete the first array element

array.shift() function can delete the first element of the array from it, And return the value of the first element; then move all remaining elements forward by 1 position to fill the gap at the head of the array.

var a = [1,2,3,4,5,6,7,8];  //定义数组
a.shift();
console.log(a);

The output result is:

How to delete elements in an array in es6

It can be seen that the above example uses a.shift() to delete the value 1 at the beginning of the a array, and then it will be repeated Set the index (restart from 0); and the shift() method will change the original array and modify the length of the array! Therefore, use console.log(a) to output the original array, which displays the array whose first element has been deleted.

Method 2: Use pop() to delete the last array element

array.pop() method can delete the last element in the array and return the deleted element.

var a = [1,2,3,4,5,6,7,8];  //定义数组
a.pop();
console.log(a)

The output result is:

How to delete elements in an array in es6

It can be seen that the above example uses a.pop() to delete the end of the a array The value is 8, and then the index will be reset (starting from 0 again); and the pop() method will also change the original array and modify the length of the array!

Method 3: Use splice() to delete any element based on the array subscript

Use splice() to delete one or more elements starting from the specified subscript position.

Syntax for deleting elements:

array.splice(index,howmany)
  • The first parameter index can specify the starting subscript position (that is, the position where the element is deleted) ;

  • The second parameter howmany specifies the number of elements that should be deleted (that is, one or more elements that need to be deleted).

Let’s take a closer look at the following example:

var arr= [1,2,3,4,5];
console.log(arr);

arr.splice(1,2);
console.log(arr);

It can be seen that: use arr.splice(1,2)Delete 2 elements starting from the position of subscript 1 (the second element of the array), that is, arr[1] and arr[2] are deleted, so the output result is :

How to delete elements in an array in es6

Using the splice() method, we can also delete elements at the beginning and end of the array:

  • If you want To delete an element at the beginning of the array, just set the value of the first parameter index of the method to 0

var arr= [1,2,3,4,5];
console.log(arr);

arr.splice(0,2);
console.log(arr);

How to delete elements in an array in es6

  • If If you want to delete elements at the end of the array, set the value of the first parameter index of the method to a negative number, then it will be positioned from the right side of the array to the left according to the absolute value; and the value of the second parameter howmany must be equal to index value.

var arr= [1,2,3,4,5];
console.log(arr);

//从倒数第二个元素开始,截取两个元素
arr.splice(-2,2);
console.log(arr);

How to delete elements in an array in es6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to delete elements in an array in es6. For more information, please follow other related articles on the PHP Chinese website!

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
React's SEO-Friendly Nature: Improving Search Engine VisibilityReact's SEO-Friendly Nature: Improving Search Engine VisibilityApr 26, 2025 am 12:27 AM

Yes,ReactapplicationscanbeSEO-friendlywithproperstrategies.1)Useserver-siderendering(SSR)withtoolslikeNext.jstogeneratefullHTMLforindexing.2)Implementstaticsitegeneration(SSG)forcontent-heavysitestopre-renderpagesatbuildtime.3)Ensureuniquetitlesandme

React's Performance Bottlenecks: Identifying and Optimizing Slow ComponentsReact's Performance Bottlenecks: Identifying and Optimizing Slow ComponentsApr 26, 2025 am 12:25 AM

React performance bottlenecks are mainly caused by inefficient rendering, unnecessary re-rendering and calculation of component internal heavy weight. 1) Use ReactDevTools to locate slow components and apply React.memo optimization. 2) Optimize useEffect to ensure that it only runs when necessary. 3) Use useMemo and useCallback for memory processing. 4) Split the large component into small components. 5) For big data lists, use virtual scrolling technology to optimize rendering. Through these methods, the performance of React applications can be significantly improved.

Alternatives to React: Exploring Other JavaScript UI Libraries and FrameworksAlternatives to React: Exploring Other JavaScript UI Libraries and FrameworksApr 26, 2025 am 12:24 AM

Someone might look for alternatives to React because of performance issues, learning curves, or exploring different UI development methods. 1) Vue.js is praised for its ease of integration and mild learning curve, suitable for small and large applications. 2) Angular is developed by Google and is suitable for large applications, with a powerful type system and dependency injection. 3) Svelte provides excellent performance and simplicity by compiling it into efficient JavaScript at build time, but its ecosystem is still growing. When choosing alternatives, they should be determined based on project needs, team experience and project size.

Keys and React's Reconciliation Algorithm: Improving PerformanceKeys and React's Reconciliation Algorithm: Improving PerformanceApr 26, 2025 am 12:21 AM

KeysinReactarespecialattributesassignedtoelementsinarraysforstableidentity,crucialforthereconciliationalgorithmwhichupdatestheDOMefficiently.1)KeyshelpReacttrackchanges,additions,orremovalsinlists.2)Usingunique,stablekeyslikeIDsratherthanindicespreve

The Boilerplate Code Required for React Projects: Reducing Setup OverheadThe Boilerplate Code Required for React Projects: Reducing Setup OverheadApr 26, 2025 am 12:19 AM

ToreducesetupoverheadinReactprojects,usetoolslikeCreateReactApp(CRA),Next.js,Gatsby,orstarterkits,andmaintainamodularstructure.1)CRAsimplifiessetupwithasinglecommand.2)Next.jsandGatsbyoffermorefeaturesbutalearningcurve.3)Starterkitsprovidecomprehensi

Understanding useState(): A Comprehensive Guide to React State ManagementUnderstanding useState(): A Comprehensive Guide to React State ManagementApr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

What are the advantages of using React?What are the advantages of using React?Apr 25, 2025 am 12:16 AM

Reactispopularduetoitscomponent-basedarchitecture,VirtualDOM,richecosystem,anddeclarativenature.1)Component-basedarchitectureallowsforreusableUIpieces,improvingmodularityandmaintainability.2)TheVirtualDOMenhancesperformancebyefficientlyupdatingtheUI.

Debugging in React: Identifying and Resolving Common IssuesDebugging in React: Identifying and Resolving Common IssuesApr 25, 2025 am 12:09 AM

TodebugReactapplicationseffectively,usethesestrategies:1)AddresspropdrillingwithContextAPIorRedux.2)HandleasynchronousoperationswithuseStateanduseEffect,usingAbortControllertopreventraceconditions.3)OptimizeperformancewithuseMemoanduseCallbacktoavoid

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.