JavaScript array element, add two functions to array, implement Delete function __ function

Source: Internet
Author: User
Tags array length javascript array

An array of JavaScript does not seem to have a default function to delete elements, when colleagues asked the next Google, found that there is no, continue to the valley to delete elements you need to do the following three steps:

1. Delete element

2. Index of all elements after the deletion of the element-1

3. Array Length-1

According to the three-step strategy above, the prototype of the lower array is expanded, and two functions are added to remove the array, which, of course, does not consider the performance issue for the time being, just to meet the daily use. The code is as follows:

<script language= "JavaScript" >

Array.prototype.removeitems=function () {

if (Arguments.length = = 0) {

Return

}else{

for (var idx in arguments) {

for (Var i=0,n=0;i<this.length;i++) {

if (!) ( THIS[I]==ARGUMENTS[IDX])) {

This[n++]=this[i];

}

}

This.length-=1;

}

}

}

Array.prototype.removeindex=function () {

if (Arguments.length = = 0) {

Return

}else{

for (var idx in arguments) {

if (isNaN (Arguments[idx])) {

Continue

}

for (Var i=0,n=0;i<this.length;i++) {

if (!) ( I==ARGUMENTS[IDX])) {

This[n++]=this[i];

}

}

This.length-=1;

}

}

}

Test code

var dd = new Array ();

Dd[0]= ' a ';

Dd[1]= ' B ';

Dd[2]= ' C ';

Dd[3]= ' E ';

Dd.removeitems (' B ', ' a ');

Dd.removeindex (1,2);

Alert (DD);

</script>

The removeitems function deletes the corresponding element values in the array, passing more than one argument and defaults to no processing when the argument is not passed.

The Removeindex function deletes the element value of the corresponding index in the array, passing multiple arguments and ignoring the arguments when the parameter is not passed or the length is tasted, when the argument is not passed by default.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.