而在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<Person> persons = new List<Person> {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對象數組,
複製代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../myjs/jquery-1.4.2.js" type="text/javascript"></script>
<script type ="text/javascript" >
$(function() {
$("p").text("這是p標籤");
});
</script>
</head>
<body>
<p></p>
<p></p> <p></p> <p></p> <p></p>
<p></p>
</body>
</html>
在瀏覽器中啟動並執行效果為:
在dom載入完成後為每一個p元素動態添加了文本,首先$("p")擷取p標籤的集合,相當於Javascript中的 document.getElementByTagName只是這裡得到的是Jquery對象的數組,這樣就有了Jquery固有的隱式迭代的功能,後面的text("這是p標籤")的操作就迭代到了每一個P標籤上,我們也可以顯示的調用each函數來顯示的迭代獲得的Jquery對象數組,下面的代碼同樣可以實現上面的效果:
複製代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../myjs/jquery-1.4.2.js" type="text/javascript"></script>
<script type ="text/javascript" >
$(function() {
$("p").each(function() {
$(this).text("這是p標籤");
});
});
</script>
</head>
<body>
<p></p>
<p></p> <p></p> <p></p> <p></p>
<p></p>
</body>
</html>