$(function () {
var arr = [1, 2, 3, 4, 5];
$.each(arr, function (index, value) {
document.write(index + ":");
document.write(value + "<br/>");
});
})
输出:
0:1
1:2
2:3
3:4
4:5$.each()遍历数组。
$(function () {
var arr = { "张三": "23","李四": 22,"王五": "21" };
$.each(arr, function (index, value) {
document.write(index + ":");
document.write(value + "<br/>");
});
})
输出:张三:23
李四:22
王五:21元素遍历
<head>
<title></title>
<script src="jQuery.1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("p").each(function () {
$(this).css("background-color", "red");
}); //一下三行代码与以上三行效果一样
//$.each($("p"), function () {
// $(this).css("background-color", "red");
//})
})
</script>
</head>
<body>
<p>我是第一个P</p>
<p>我是第二个P</p>
<p>我是第三个P</p>
<p>我是第四个P</p>
<p>我是第五个P</p>
</body>
</html>
四、$.grep()
筛选符合条件的元素,返回一个新数组
语法:$.grep(Arrar,fn(value,index)); 要注意下回调函数的参数的顺序,第一个是值,第二个是索引。
$.grep(Arrar,fn(value,index),[bool]); 第三个参数表示是否取反,true表示取反,false表示不取反。
$(function () {
var arr = [2, 5, 34, 22, 8];
var arr1 = $.grep(arr, function(value, index) {
return index <= 2 && value < 10;
})
document.write(arr1.join()); //输出2,5
})六、$.map()
改变函数内的数据,接受一个数组或类数组对象作为参数
$(function () {
var arr = [2, 5, 34, 22, 8];
var arr1 = $.map(arr, function (value, index) {
if (value > 5 && index < 3) {
return value - 10;
}
})
document.write(arr.join() + "<br/>"); //2,5,34,22,8 可以看到原数组不改变
document.write(arr1.join()); //24 新数组只获得了操作之后的结果
})七、$.inArray()










