Home>

1. Delete the specified element in the array

/**
 * Reference example
foreach=function (obj, insp) {
If (obj == null&&obj.constructor!=Array) {
Return [];
}
//obj is the array to be processed,obj == null means that the object does not exist yet;
obj.constructor!=array indicates that the constructor of the property of the object obj is not an array;
//constructor attribute always points to the constructor that created the current object.
Both conditions are met,Returns an empty array [];
//Let's take a closer look at the constructor property.
var obj=[1, 2, 3, 4];//equivalent to var obj=new array (1, 2, 3, 4);
console.log (obj.constructor === array);//returns true to indicate that the constructor of obj is an array;
var foo=function () {};//equivalent to var foo=new function ();
console.log (foo.constructor === function);//returns true to indicate that foo's constructor is a function;
var obj=new foo ();//Instantiate an obj object by the constructor
console.log (obj.constructor === foo);//returns true to indicate that obj's constructor is foo;
 * /
//Delete the specified element in the array
function del (val, arr)
{
  //Detection parameters
  if (arr == null&&arr.constructor!=array) {
    return [];
  }
  var newarr=[];//Save to new array if it doesn't exist
  for (var i=0;i<arr.length;i ++) {
    if (arr [i]!=val)
      newarr.push (arr [i]);
  }
  return newarr;
}
alert (del (2, [1, 2, 3, 4, 5, 2]));

2. Remove duplicate elements

/**
 * Remove duplicate elements from an array
Store the value of the element as the key of a new array. The key cannot be repeated.
Then the variable degree group can be
 * /
function unique (data) {
  data=data || [];
  var a=();
  len=data.length;
  for (var i=0;i<len;i ++) {
    var v=data [i];
    if (typeof (a [v]) == "undefined") {
      a [v]=1;
    }
  };
  data.length=0;
  for (var i in a) {
    data [data.length]=i;
  }
  return data;
}
alert (unique ([12,12,12,34]));

3. Delete the specified index of the array

/**
 * Remove the specified index element of the array
 *
 * The value of i is always changing,The value of n is only changed when the if condition is satisfied (it will increase in order)
 * /
array.prototype.remove=function (dx)
 {
  if (isnan (dx) || dx>this.length) {return false;}
  for (var i=0, n=0;i<this.length;i ++)
  {
    if (this [i]!=this [dx])
    {
      this [n ++]=this [i]
    }
  }
  this.length-=1
 }
var arr=[1,2,3,4,2,5];
alert (arr);
arr.remove (2);
alert (arr);
  • Previous C # method of operating the registry
  • Next Analysis of the difference between js form submission and submit submission