在Object内部时,数组长度为0

时间:2014-01-08 15:17:21

标签: javascript jquery

我正在尝试制作两张专辑的喜欢数量的条形图。我无法弄清楚为什么array.length返回0.我尝试使用新的Array()来声明数组。

在generateBarGraph()函数中,我使用console.log()来查看数组,但它显示“Array [0]”,我认为它的长度为0,但当我关闭控制台并重新加载页面时,则打开再次控制台显示“数组[2]”。我真的很困惑这个问题。有人能帮助我吗?

$(document).ready(function () {
    // constants
    var constants = {
        'column': 'col',
        'bar': 'bar'
    };

    // create a global data variable
    var data;

    $.ajaxSetup({
        cache: true
    });

    // load the SDK asynchronously
    $.ajax({
        url: 'http://connect.facebook.net/en_UK/all.js',
        dataType: 'script',
        timeout: 5000, // call the error function after 5 seconds

    }).done(function (data, txtStat) {
        console.log('Facebook JavaScript SDK loaded');

        // use application id for authentication
        FB.init({
            appId: '1392455751007269',
        });

        // make sure that div#fb-likes is present in html file
        if (!($('#fb-likes')[0])) {
            console.warn('The \"fb-likes\" div has not been created, auto-creating');

            // div#fb-likes
            var $div = $('<div>', {
                id: 'fb-likes',
                class: 'clearfix'
            });

            // add element to body
            $('body').append($div);
        }

        // fetch Facebook likes once and every given seconds thereafter
        generateBarGraph();
        /*setInterval(function() {
            rt_fb_likes(likes, captions, count);
        }, 2000);*/

    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.error('Failed to load Facebook JavaScript SDK');

        // create "no internet connection" text
        var $no_net = $('<span>', {
            id: 'no-net',
            html: 'Connection error<small>Please reload the page</small>'
        });
        $('#fb-likes').html($no_net);

        // center text vertically and horizontally
        $no_net.css({
            'margin-left': $no_net.width() / -2,
            'margin-top': $no_net.height() / -2
        });
    });

    /**
     * Generate Facebook like bar graph.
     */
    function generateBarGraph() {
        // get facebook likes
        data = fbLikes();

        // no data is returned
        if (data === false) {
            return false;
        }

        // build html content
        var content = '';
        for (var i = 0; i < data.likes.length; i++) {
            $('#fb-likes').append(
                $('<div>', {
                    'class': constants.column
                })
            );
        }

        // this is where the problem is..
        console.log(data.likes);
        for (var i = 0; i < data.likes.length; i++) {
            for (var j = 0; j < data.likes[i].length; j++) {
                $('.' + constants.column).append(
                    $('<div>', {
                        'class': constants.bar
                    })
                )
            }
        }
    }

    /**
     * Gets Facebook likes of two albums.
     * Assuming there is an internet on first call.
     */
    function fbLikes() {
        var header = 'Mr. and Ms. Engineering 2014 - UE Caloocan\n';

        var ad = '\n\nHairstyle and make-up by Aloja Carvajal'
               + '\nPhoto by Willie De Vera for Portraits Plus Ph';

        var ad1 = '\n\nHairstyle and make-up by Aloja Carvajall'
                + '\nPhoto by Willie De Vera for Portraits Plus Ph';

        // likes and captions array
        var r = {                
            'captions': [
                [],
                []
            ],

            'likes': [
                [],
                []
            ]
        };

        // query facebook for the number of likes and the captions of the photo
        FB.api({
                method: 'fql.multiquery',
                queries: {
                    // boys's query
                    boys: 'SELECT like_info.like_count, caption FROM photo '
                        + 'WHERE pid IN (SELECT pid FROM photo WHERE aid = '
                        + '"177640942437303_1073741838")',

                    // girls's query
                    girls: 'SELECT like_info.like_count, caption FROM photo '
                         + 'WHERE pid IN (SELECT pid FROM photo WHERE aid = '
                         + '"177640942437303_1073741837")'
                }
            },

            function (response) {
                // failed to get resource
                if (response.error) {
                    console.warn('Unable to get data');

                    return false;
                }

                // store things in new arrays
                for (var i = 0; i < 2; i++) {
                    var result = response[i].fql_result_set;

                    for (var j = 0; j < result.length; j++) {
                        // store like count
                        r.likes[i][j] = result[j].like_info.like_count;

                        // remove ads from caption then store them
                        r.captions[i][j] = result[j].caption
                            .replace(ad, '')
                            .replace(ad1, '')
                            .replace(header, '');
                    }
                }

                // sort in descending order
                /*for (var i = 0; i < 2; i++) {
                    likes[i].sort(function (a, b) {
                        return b - a;
                    });
                }*/
            }
        );

        return r;
    };

0 个答案:

没有答案