In the array object there is a given function can delete the specified elements in the array, although very useful, but the total feel is not touching the more awkward, the following share a custom delete array specified index value elements of the function, I hope to give you a new idea.
The code example is as follows:
var array=[];
array[0]= "cloud-dwelling community one";
array[1]= "cloud-dwelling Community II";
array[2]= "cloud-dwelling community three";
array[3]= "cloud-dwelling community four";
array[4]= "cloud-dwelling community five";
function Remove (Array,index)
{
if (index<= (array.length-1))
{for
(var i=index;i< array.length;i++)
{
array[i]=array[i+1];
}
}
else
{
throw new Error (' exceeds maximum index! ');
}
array.length=array.length-1;
return array;
}
In the above code, declare a remove () function that has two arguments, the first argument is an array object, and the second parameter is the index value of the array element to be deleted, so the above code can delete the third element in the array and output the array that deletes the element's user. The principle of implementation is also very simple, do a simple introduction:
The Remove () function first determines whether the incoming index value is approximately array.length-1 the maximum index value of the array, or if it is greater than, throws an error, otherwise it uses the For loop to begin traversing the index value I, setting the array value of index I to the low i+1 item, and so on. The principle is generally so, if have any question can post a message.
PS:JS Delete array specified element
var a = new Array (" A "," B "," CC "," D3 ");//delete the CC element//jquery.inarray () function of a array to search for the specified value in the array. and returns its index value.
Returns-1 if the value is not present in the array. This function belongs to the global jquery object.
The static method added in jquery 1.2 is var index = $.inarray ("CC", a); if (index>=0) {//arrayobject.splice (index,howmany,item1,....., itemx)//Parameter description//index required.
Integer that stipulates where to add/remove items, and use negative numbers to specify the position from the end of the array. Howmany required. The number of items to delete.
If set to 0, the item is not deleted. Item1, ..., itemx Optional.
The new item to add to the array.
A.splice (index,1);
Alert (a.tostring ());
}else{alert ("Error");
return false; }