Home > Web Front-end > JS Tutorial > A simple example of javascript deleting array elements and reducing the array length_javascript skills

A simple example of javascript deleting array elements and reducing the array length_javascript skills

WBOY
Release: 2016-05-16 17:00:02
Original
1332 people have browsed it

The example is as follows:

Copy the code The code is as follows:

/**
* Delete array elements by value
*
* @param mixed value element value
* @returns array
*/
Array.prototype.deleteValue = function(value){
var i = 0;
for(i in this){
if(this[i] = = value) break;
}
return this.slice(0, i).concat(this.slice(parseInt(i, 10) 1));
}

//Example
var test = new Array(1,5,3,4,2);
//Output 5
console.log(test.length);
// Delete the element with value 4
test = test.deleteValue(4);
//Output [1, 5, 3, 2]
console.log(test);
//Output 4
console.log(test.length);

/**
* Delete array elements by index
*
* @param int index element index
* @returns array
*/
Array.prototype.deleteIndex = function(index){
return this.slice(0, index).concat(this.slice(parseInt(index, 10) 1));
}

//Example
var test = new Array(1,5,3,4,2);
//Output 5
console.log(test.length);
// Delete the element with index 1
test = test.deleteIndex(1);
//Output [1, 3, 4, 2]
console.log(test);
//Output 4
console.log(test.length);

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template