Javascript methods to remove array elements: 1. Remove array elements through the length attribute; 2. Remove through the delete keyword; 3. Remove through the stack method; 4. Remove through the queue method; 5 , removed through the operation method; 6. removed through the iterative method; 7. removed through the prototype method.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
A summary of seven methods to delete array elements in JavaScript
at In JavaScript, besides Object, the Array type is probably the most commonly used type. There is a big difference from arrays in other languages. Arrays in JavaScript are very flexible. Today I will summarize the method of Array deletion in JavaScript. Rough classification can be divided into the following categories:
1. length
2. delete
3. Stack method
4. Queue method
5. Operation method
6. Iteration method
7. Prototype method
Below I will give examples and explanations of the above methods one by one.
1. length
JavaScript中Array的length属性非常有特点一一它不是只读的。因此,通过设置这个属性可以从数组的末尾移除项或添加新项,请看下面例子:
var colors = ["red", "blue", "grey"]; //创建一个包含3个字符串的数组colors.length = 2; console.log(colors[2]); //undefined
2. delete keyword
var arr = [1, 2, 3, 4];delete arr[0];console.log(arr); //[undefined, 2, 3, 4]
It can be seen that the length of the array remains unchanged after delete, but the deleted element is set to undefined.
3. Stack method
var colors = ["red", "blue", "grey"]; var item = colors.pop(); console.log(item); //"grey"console.log(colors.length); //2
It can be seen that when the Pop method is called, the array returns the last item, which is "grey", and there are only two elements left in the array.
4. Queue method
The access rule of the queue data structure is FIFO (first in, first out). The queue adds items at the end of the list and removes items from the front of the list. Use shift method, which removes the first item in the array and returns it with the length of the array reduced by 1.
var colors = ["red", "blue", "grey"]; var item = colors.shift(); console.log(item); //"red"console.log(colors.length); //2
5. Operation method
splice() is probably the most powerful array method. There are many ways to use it. Here we only introduce the method of deleting array elements. . When deleting array elements, it can delete any number of items. You only need to specify 2 parameters: the position of the first item to be deleted and the number of items to be deleted. For example, splice(0, 2) will delete the first item in the array. Two items.
var colors = ["red", "blue", "grey"];var item = colors.splice(0, 1);console.log(item); //"red"console.log(colors); //["blue", "grey"]
[Recommended learning: javascript advanced tutorial】
6. Iterative method
The so-called iterative method It is to use a loop to iterate the array elements and delete the items that match the items to be deleted. The most commonly used place may be when the elements in the array are objects, and the array elements are deleted based on the attributes of the objects such as IDs, etc. Two methods are introduced below:
The first one uses the most common ForEach loop to compare the elements and delete them after finding them:
var colors = ["red", "blue", "grey"]; colors.forEach(function(item, index, arr) { if(item == "red") { arr.splice(index, 1); } });
The second one uses the filter method in the loop:
var colors = ["red", "blue", "grey"]; colors = colors.filter(function(item) { return item != "red"}); console.log(colors); //["blue", "grey"]
The code is very simple. Find out the number of items whose elements are not "red" and return it to colors (in fact, you get a new array), so as to achieve the effect of deletion.
7. Prototype method
The purpose of deletion is achieved by adding a method to the Array prototype:
Array.prototype.remove = function(dx) { if(isNaN(dx) || dx > this.length){ return false; } for(var i = 0,n = 0;i < this.length; i++) { if(this[i] != this[dx]) { this[n++] = this[i]; } } this.length -= 1; };var colors = ["red", "blue", "grey"]; colors.remove(1); console.log(colors); //["red", "grey"]
Here the deletion method is added to the Array. Prototype object, all Array objects in this environment can use this method. Although it is possible to do so, we do not recommend modifying native object prototypes in production applications. The reason is simple. If you add this method to the prototype of a native object because a certain method is missing in an implementation, it may cause a naming conflict when the code is run in another implementation that supports this method. And doing so may accidentally lead to overriding native methods.
Here, I have summarized the commonly used methods of deleting elements in JavaScript Array. Everyone is welcome to add.
The above is the detailed content of How to remove array elements in javascript. For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools