Home Web Front-end JS Tutorial Introduction to JS functions for deleting array elements_javascript skills

Introduction to JS functions for deleting array elements_javascript skills

May 16, 2016 pm 05:39 PM
Delete array elements

split code to convert a string into an array and output it:

Copy code The code is as follows:





js delete array elements:
var arr=['a','b','c'];To delete the 'b', there are two methods:

1.delete method: delete arr[1]

In this way, the length of the array remains unchanged. At this time, arr[1] becomes undefined, but it also has the advantage that the index of the original array remains unchanged. At this time, you can use


Copy code

The code is as follows: for(index in arr) {   document.write ('arr[' index ']=' arr[index]);
}



This traversal method skips undefined elements

* This method will be supported by IE4.o from now on


2. Array object splice method: arr.splice(1,1);

In this way, the array length changes accordingly, but the original array index also changes accordingly

The first 1 in the splice parameter is the starting index of deletion (counted from 0), here it is the second element of the array The second 1 is the number of elements to delete, here only one element is deleted , that is, 'b';
At this time, you can traverse the array elements in the normal way of traversing the array, such as for, because the deleted elements are not retained in the
array

* This method is only supported after IE5.5

It is worth mentioning that while the splice method deletes array elements, it can also add new array elements
For example, arr.splice(1,1,'d','e'), d, e The elements are added to the array arr

The resulting array becomes arr:'a','d','e','c'

JavaScript truncates an array by setting the length property of the array. The only way to shorten the length of an array is to use the delete operator to delete an element in the array. Although that element becomes undefined, the length property of the array does not There are two ways to delete elements and change the length of the array without changing.


/*
* Method: Array.remove(dx)

* Function: Delete array element.

* Parameter: dx subscript of deleted element.

* Return: Modify on the original array Array

*/
 
 //It is often used to reconstruct the array through traversal.




Copy code

The code is as follows:Array.prototype.remove=function(dx) { if(isNaN(dx)||dx>this.length){return false;}
for(var i=0,n=0;i{
if(this[i]!=this[dx])
🎜>}
a = ['1','2','3','4','5'];
alert("elements: " a "nLength: " a.length);
a.remove(0); //Delete the element with subscript 0
alert("elements: " a "nLength: " a.length);







Copy code


The code is as follows:

/*

* Method: Array.baoremove( dx) * Function: Delete array element. * Parameter: dx subscript of deleted element. * Return: Modify the array on the original array. */// We can also use splice to achieve it.
 this.splice(dx,1);
}
b = ['1','2','3','4','5'];
alert("elements : " b "nLength: " b.length);
b.baoremove(1); //Delete the element with index 1
alert("elements: " b "nLength: " b.length);

IE5 이하 버전에서는 JavaScript의 Array 객체가 배열 요소를 삭제하는 기성 메서드를 제공하지 않는다는 것을 알고 있습니다. IE5.5 버전에서는 splice 방식이 있기는 하지만 특정 항목(또는 여러 항목)을 삭제하지는 않고, 특정 항목(또는 여러 항목)의 값만 삭제하므로 해당 항목이 여전히 존재한다는 의미이다. 배열의 길이는 변경되지 않았습니다.

실제로 배열에 삭제 메소드를 직접 추가할 수 있습니다(실제로 배열 구성원에서 배열 항목을 제거하는 것을 의미합니다). 아마도 루프를 사용하여 배열을 재할당하는 것을 생각할 수도 있지만 이는 매우 비효율적입니다.

다음으로 Array 객체의 두 가지 방법인 Slice와 Concat을 사용하여 배열 삭제를 사용자 정의하는 방법을 소개합니다.

구체적인 코드는 다음과 같으니, 안에 있는 댓글을 주목해주세요.

코드 복사 코드는 다음과 같습니다.

Array.prototype.del=function(n ) { / /n은 0부터 시작하는 숫자를 나타냅니다.
//Prototype은 객체 프로토타입입니다. 여기에서 객체에 사용자 정의 메소드를 추가하는 방법을 참고하세요.
if(n 이것을 반환합니다.
else
return this.slice(0,n).concat(this.slice(n 1,this.length)); 두 개 이상의 배열로 구성된 새 배열입니다.
     여기에 this.slice(0,n)/this.slice(n 1,this.length)를 반환하는 새로운 배열이 있습니다.         
슬라이스 메서드: 시작 위치와 끝 위치를 각각 지정하는 두 개의 매개변수를 사용하여 배열의 세그먼트를 반환합니다.
 */
}
//이 방법을 직접 추가해 보겠습니다.
var test=new Array(0,1,2,3,4,5);
test =test .del(3); //0부터 계산하면 여기서 4번째 항목이 삭제됩니다.
alert(test);


이런 방식으로 요구 사항을 충족하기 위해 Array 객체의 두 가지 메서드만 사용합니다.
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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles