Home >Web Front-end >JS Tutorial >Extension implementation code collection of javascript array_javascript skills

Extension implementation code collection of javascript array_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:04:13801browse

Array.prototype.del = function(n)
{
if (n return this.slice(0,n).concat(this.slice(n 1,this. length));
}
//Array shuffle
Array.prototype.random = function()
{
var nr=[], me=this, t;
while(me.length>0)
{
nr[nr.length] = me[t = Math.floor(Math.random() * me.length)];
me = me.del (t);
}
return nr;
}
//Number array sorting
Array.prototype.sortNum = function(f)
{
if (!f ) f=0;
if (f==1) return this.sort(function(a,b){return b-a;});
return this.sort(function(a,b){return a-b ;});
}
// Get the maximum item of the numeric array
Array.prototype.getMax = function()
{
return this.sortNum(1)[0];
}
// Get the minimum item of the numeric array
Array.prototype.getMin = function()
{
return this.sortNum(0)[0];
}
//The position where the specified element value first appears in the array
Array.prototype.indexOf = function(o)
{
for (var i=0; i return -1;
}
// Remove duplicate items in the array
Array.prototype.removeRepeat=function()
{
this.sort();
var rs = [];
var cr = false;
for (var i=0; i {
if (!cr) cr = this[i];
else if (cr==this[i]) rs[rs.length] = i;
else cr = this[i];
}
var re = this;
for (var i=rs.length-1; i>=0; i--) re = re.del(rs[i]);
return re;
}

Example:
var arr=["ni","wo","ta"];
Delete "wo" in the array
var newArr=arr. del(1);
Returns the position where "me" first appears in the array, if not, returns -1
var strPos=arr.indexOf("me");

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