Extended example code of JS array_javascript skills
- WBOYOriginal
- 2016-05-16 19:02:50917browse
Array.prototype.del = function(n)
{
if (nreturn this.slice(0,n).concat(this.slice (n 1,this.length));
}
//Array shuffling
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; ireturn -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
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