jQuery 学习笔记之$.each()

jQuery 学习笔记之$.each()

本文目标

1、$.each()的使用场景
2、实现continuebreak的效果

学习资料

官方描述文档: http://api.jquery.com/jQuery.each/
中文描述文档: http://www.css88.com/jqapi-1.9/jQuery.each/
建议: 如果时间充裕还是看官方文档

官方描述

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function’s arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

一个被用于遍历对象(objects)和数组(arrays)的迭代函数。数组和有长度属性的类数组(例如一个函数的参赛对象)根据数字索引进行遍历,索引值的范围为0~length-1,其它对象是根据他们的属性名称进行遍历。

调用方式

$.each(param1,param2)
参数说明:
param1: 待遍历的数组(array)或对象(object)
param2: 回调函数,每一个迭代元素都将用于该回调函数。如果param1是数组(或类数组),则回调函数的形式为Function( Integer indexInArray, Object value ),如果param1是对象,则回调函数的形式为Function( String propertyName, Object valueOfProperty )

The .each()functionisnotthesameas (selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

$.each()$(selector).each()不一样,$(selector).each()仅被用于遍历jQuery对象。$.each()用于迭代任何一个集合,这个集合可以是一个对象也可以是一个数组。就数组而言,回调函数每次被执行时传递一个数字下标和下标对应的值。下标对应的值可以利用this`关键字代替,无论这个值是一个简单的字符串还是数字,JavaScript总是将这个值封装成一个对象。这个方法返回它的第一个参数做为返回值。

源码
    each: function( obj, callback ) {
        var length, i = 0;

        if ( isArrayLike( obj ) ) {
            length = obj.length;
            for ( ; i < length; i++ ) {
                if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
                    break;
                }
            }
        } else {
            for ( i in obj ) {
                if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
                    break;
                }
            }
        }

        return obj;
    }
    function isArrayLike( obj ) {

        // Support: iOS 8.2 (not reproducible in simulator)
        // `in` check used to prevent JIT error (gh-2145)
        // hasOwn isn't used here due to false negatives
        // regarding Nodelist length in IE
        var length = !!obj && "length" in obj && obj.length,
            type = jQuery.type( obj );

        if ( type === "function" || jQuery.isWindow( obj ) ) {
            return false;
        }

        return type === "array" || length === 0 ||
            typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
实现breakcontinue效果

$.each()用于迭代集合中的每一个元素,其效果等同于for()循环。既然如此,那如何实现breakcontinue的效果呢?

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

    for ( ; i < length; i++ ) {
        if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
            break;
        }
    }

    for ( i in obj ) {
        if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
            break;
        }
    }

由上面的源代码可知,当回调函数中返回false时,退出循环;当回调函数返回非false时,本次循环结束,继续下一次循环

意外结果

each()内部根据isArrayLike()的返回值决定集合的遍历方式,而isArrayLike()的返回值又受到length属性的影响。故当集合中含有length属性时,回调函数可能无法达到预期效果。

    return type === "array" || length === 0 ||
            typeof length === "number" && length > 0 && ( length - 1 ) in obj;
example

测试以下四种情况,看看结果与你预期的效果是否一样。

    function testEach(){
        var tObj = {bar: 'foo', length: 10, 9:'a'};//or length: 0
        //var tObj = [ "one", "two", "three", "four", "five" ];
        //var tObj = { one: 1, two: 2, three: 3, four: 4, five: 5 };
        //debugger;
        $.each(tObj,function(index,value){
            alert(this+'   '+value);
        });
    }
类数组

上文中有提到类数组,那什么是类数组呢?

对于一个普通的对象来说,如果它的所有property名均为正整数,同时也有相应的length属性,那么虽然该对象并不是由Array构造函数所创建的,它依然呈现出数组的行为,在这种情况下,这些对象被称为“类数组对象”。
资料来源:http://www.jb51.net/article/59169.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值