Analysis on the method for deleting a specified element from the jquery array: grep (), jquerygrep
Problems encountered
Today, we encountered a problem: deleting a specified Element in the array and returning a new array.
The js array I defined is as follows:
var sexList=new Array[3];sexList[0]="1";sexList[1]="2";sexList[2]="";
Expected results
The result I want to achieve is as follows:
Delete the element with Index = 1 and return the new array.
The returned result is:
var sexList=new Array("1","");
We know that the native javascript has a function: the splice () method, which can delete specified elements in the array.
On the specific usage of splice () method, you can refer to the description of w3school, here do not explain: http://www.w3school.com.cn/jsref/jsref_splice.asp
Use the implementation code of splice ()
My implementation code:
var sexList=new Array[3];sexList[0]="1";sexList[1]="2";sexList[2]="";sexList=sexList.splice(1,1);
However, I found that when my array uses this method, the returned array is not as expected. Returns an empty string.
Later, I searched for jquery related APIs online and found a function: grep ()
Grep () Usage
JQuery. grep (array, callback, [invert])
Overview
Filter Array elements using the filter function.
This function must pass at least two parameters: the array to be filtered and the filter function. The filter function must return true to retain the element or false to delete the element.
Parameters
English name |
Parameter description |
Array: |
Array to be filtered. |
Callback: |
This function processes each element of the array. The first parameter is the current element, the second parameter is the element index value. This function should return a Boolean value. In addition, this function can be set to a string. When it is set to a string, it will be treated as "lambda-form" (abbreviated form ?), A Indicates the array element, And I indicates the element index value. For example, "a> 0" indicates "function (a) {return a> 0 ;}". |
Invert: |
If "invert" is false or set, the function returns the elements returned by the filter function in the array to true. If "invert" is true, the system returns the Element Set of false in the filter function. |
Implementation code using grep ()
sexList=$.grep(sexList,function(n,i){return i!=1;});
Function (n, I)
N: represents a single object of the array,
I: indicates the index of the array.
The above analysis shows how to delete a specified element from the jquery array: grep () is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's house.