如何在jQuery中使用数组
数组是一种线性数据结构。JavaScript中的数组是具有一些内置方法的可变列表,我们可以使用数组字面来定义数组。
语法和声明:
var arr1=[];
var arr2=[1,2,3];
var arr2=["India","usa","uk"];
数组的类型:数组的类型是” 对象 ”
var arr=[1,2,3];
console.log(typeof(arr)); //--> object
迭代方法:我们使用数组的长度属性在数组中进行迭代。
var arr=[1,2,3];
for(var i=0;i<arr.length;i++)
{
console.log(arr[i]);
}
输出:
1
2
3
使用JQuery的迭代方法:jQuery提供了一个通用的.each函数来迭代数组的元素,以及对象的属性。jquery .each()函数可以用来迭代任何集合,不管它是一个对象还是一个数组。
在数组的情况下,回调每次都会传递一个数组索引和一个相应的数组值。(值也可以通过这个关键字访问,但Javascript总是把这个值包装成一个Object,即使它是一个简单的字符串或数字值。)该方法返回其第一个参数,即被迭代的对象。
var arr = [ "hello","from","Gfg" ];
jQuery.each( arr, function( index, value ) {
// Index represents key
// Value represents value
console.log( "index", index, "value", value );
});
输出:
index 0 value hello
index 1 value from
index 2 value Gfg
示例:
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 method
console.log("traversing in array using jQuery");
jquery.each(arr, function(index,value) {
console.log('index: ' + index + ' ' + 'value: ' + value);
});
输出: