在迭代对象时获取TypeError

时间:2015-10-08 07:31:02

标签: javascript jquery

我正在使用Rails,我的jQuery代码出错:

Uncaught TypeError: Cannot read property 'length' of undefined

我收到错误的实际代码:

// args is for internal usage only
    each: function( obj, callback, args ) {
        var value,
            i = 0,
            length = obj.length,
            isArray = isArraylike( obj );

        if ( args ) {
            if ( isArray ) {
                for ( ; i < length; i++ ) {
                    value = callback.apply( obj[ i ], args );

                    if ( value === false ) {
                        break;
                    }
                }
            } else {
                for ( i in obj ) {
                    value = callback.apply( obj[ i ], args );

                    if ( value === false ) {
                        break;
                    }
                }
            }

1 个答案:

答案 0 :(得分:3)

试试这个怎么样?

var length = Object.keys(obj).length

var length = 0;
for (var o in obj) {
    length++;
}