How to remove array elements in javascript
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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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