
而在Jquery中則使用$.map()、$.each()來操作數(shù)組:
首先是普通的數(shù)組(索引為整數(shù)的數(shù)組):
代碼如下:
$.map(arr,fn);
對數(shù)組中的每個元素調(diào)用fn函數(shù)逐個進行處理,fn函數(shù)將處理返回最后得到的一個新的數(shù)組
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)對數(shù)組array每個元素調(diào)用fn函數(shù)進行處理,沒有返回值
var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
$.each(arr, function(key, value) { alert("key:" + key + "value:" + value); });
還可以省略function的參數(shù),這個時候this可以得到遍歷的當(dāng)前元素的值
var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
$.each(arr, function() { alert(this); });
然后是索引為字符串的 鍵值對數(shù)組,針對這類數(shù)組,
一般采用$.each(array,fn)來操作:
var arr = { "jim": "11", "tom": "12", "lilei": "13" };
$.each(arr, function(key, value) { alert("姓名:"+key+"年齡:"+value); });
當(dāng)然也可以使用無參的的function進行遍歷;
當(dāng)這類數(shù)據(jù)從服務(wù)器端獲取時可以如下進行:
服務(wù)器端:
代碼如下:
<%@ 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()將后臺傳遞過來的字符串轉(zhuǎn)化為js數(shù)組對象,接下來我們就使用操作普通數(shù)組的方式來操作這個得到的數(shù)組
第三種就是通過標簽選擇器獲取的Jquery對象數(shù)組,
代碼如下:
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com