Home >Web Front-end >JS Tutorial >jQuery Learning 7 Functions to Manipulate JavaScript Objects and Collections_jquery
Remove leading and trailing null characters from the string : $.trim()
Like many high-level languages that provide similar functions, the jQuery class library also provides such functions. Specific usage: $.trim(value) removes the leading and trailing blank characters from the passed in string and returns the result.
Iterate over properties and collections:
You can use the following methods to operate arrays and objects in JavaScript:
var anArray = ['one','two','three'];
for(var n = 0; n < anArray.length; n ){...}
var anObject = {one:1, two:2, three:3};
for(var p in anObject){...}
In jQuery, $.each(container,callback) is provided to iterate each item of the passed in container and call the passed callback function for each item.
This function can iterate over arrays or objects in the same format:
var anArray = ['one','two','three'];
$.each(anArray,function(n,value){...});
var anObject = {one:1, two:2, three:3};
$.each(anObject,function(name,value){...});
Filter the array:
Traversing an array in order to find elements matching specific criteria is a frequent requirement for applications that process large amounts of data. jQuery provides the $.grep() function to implement this function.
$.grep(array,callback,invert) traverses the passed array and calls the callback function for each element. The return value of the callback function determines whether to collect the current elements into a new array (the new array is returned as the value of the $.grep() function).
If you want to filter an array and get all values greater than 100:
var bigNumber = $.grep(originalArray,function(value){return value > 100;});
Whether the array contains a specific value or the subscript value of a specific value in the array:
$.inArray(value,array) returns the index of the first occurrence of the passed value in the array.
var index = $.inArray(2,[1,2,3,4,5]); The result is that the subscript value 1 is returned and assigned to the index variable.