for in、each; for 、forEach、map

时间:2025-01-31 23:07:50

1、jQuery.each(object, [callback])

用于例遍任何对象。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。

2、 for...in 语句用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)

3、 数组循环变量,最先想到的就是 for(var i=0;i<count;i++)这样的方式了。 除此之外,也可以使用较简便的forEach 方式

4、map() 把每个元素通过函数传递到当前匹配集合中,生成包含返回值的新的 jQuery 对象。由于返回值是 jQuery 封装的数组,使用 get() 来处理返回的对象以得到基础的数组。

!function(){
var aa = {
a:"",
b:"",
c:""
} for(var i in aa){
console.log("for in :"+i)
} $.each(aa,function(index,value){
console.log(index)
}) var bb=["","",""];
bb.forEach(function(a,b,c){
console.log(a)
});
}()
//Array.forEach implementation for IE support..
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> ; // Hack to convert O.length to a UInt32
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
k = ;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
<form method="post" action="">
<fieldset>
<div>
<label for="two"></label>
<input type="checkbox" value="" id="two" name="number[]">
</div>
<div>
<label for="four"></label>
<input type="checkbox" value="" id="four" name="number[]">
</div>
<div>
<label for="six"></label>
<input type="checkbox" value="" id="six" name="number[]">
</div>
<div>
<label for="eight"></label>
<input type="checkbox" value="" id="eight" name="number[]">
</div>
</fieldset>
</form> <script>
$(':checkbox').map(function() {
return this.id;
}).get().join(',');
</script>