
而在Jquery中則使用$.map()、$.each()來操作數組:
首先是普通的數組(索引為整數的數組):
代碼如下:
$.map(arr,fn);
對數組中的每個元素調用fn函數逐個進行處理,fn函數將處理返回最后得到的一個新的數組
var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
var newarr = $.map(arr, function(item) {return item*2 });
alert(newarr);
$.each(array,fn)對數組array每個元素調用fn函數進行處理,沒有返回值
var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
$.each(arr, function(key, value) { alert("key:" + key + "value:" + value); });
還可以省略function的參數,這個時候this可以得到遍歷的當前元素的值
var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
$.each(arr, function() { alert(this); });
然后是索引為字符串的 鍵值對數組,針對這類數組,
一般采用$.each(array,fn)來操作:
var arr = { "jim": "11", "tom": "12", "lilei": "13" };
$.each(arr, function(key, value) { alert("姓名:"+key+"年齡:"+value); });
當然也可以使用無參的的function進行遍歷;
當這類數據從服務器端獲取時可以如下進行:
服務器端:
代碼如下:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
Person p1 = new Person { Age = "22", Name = "tom" };
Person p2 = new Person { Age = "23", Name = "jim" };
Person p3 = new Person { Age = "24", Name = "lilei" };
IList
persons = new List {p1,p2,p3};
JavaScriptSerializer js = new JavaScriptSerializer();
string s= js.Serialize(persons);
context.Response.Write(s);
}
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
}
public bool IsReusable {
get {
return false;
}
}
}
先實例化了三個person對象,然后放到一個集合中,最后把這個集合序列化成字符串流到客戶端;
客戶端:
客戶端通過$.parseJSON()將后臺傳遞過來的字符串轉化為js數組對象,接下來我們就使用操作普通數組的方式來操作這個得到的數組
第三種就是通過標簽選擇器獲取的Jquery對象數組,
代碼如下:
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com