How to use array with jQuery ?
The array is a linear data structure. Arrays in JavaScript are mutable lists with a few built-in methods, we can define arrays using the array literal.
Syntax And Declaration:
var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"];
Type of Array: The type of an array is “object“.
var arr=[1,2,3]; console.log(typeof(arr)); //--> object
Iteration Approach: We use the length property of the array to iterate in the array.
var arr=[1,2,3];
for(var i=0;i<arr.length;i++)
{
console.log(arr[i]);
}Output:
1 2 3
Iteration Approach using JQuery: jQuery provides a generic .each function to iterate over elements of arrays, as well as properties of objects. The jquery .each() function can be used to iterate over any collection, whether it is an object or an array.
In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through this keyword, but Javascript will always wrap this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
var arr = [ "hello","from","Gfg" ];
jQuery.each( arr, function( index, value ) {
// Index represents key
// Value represents value
console.log( "index", index, "value", value );
});Output:
index 0 value hello index 1 value from index 2 value Gfg
Example:
Javascript
const jsdom = require('jsdom');const dom = new jsdom.JSDOM("");const jquery = require('jquery')(dom.window);// Usually we traverse console.log("Simply traversing in array");var arr=["hello","from","GFG"];for(var i=0;i<arr.length;i++){ console.log(arr[i]);}console.log("type of array -> "+typeof(arr));// Traversing using jQuery methodconsole.log("traversing in array using jQuery");jquery.each(arr, function(index,value) { console.log('index: ' + index + ' ' + 'value: ' + value);}); |
Output:



