为什么我的JavaScript函数没有填充数组? [英] Why is my JavaScript function not populating my array?

查看:160
本文介绍了为什么我的JavaScript函数没有填充数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码块成功返回数组值(编号1 130879253000、34756)

The following block of code successfully returns array values (No. 1 130879253000, 34756)

    function getCsv(file_name){
        var array_holder = [];
        $.get(file_name, function(csv, state, xhr) {

            // inconsistency
            if (typeof csv != 'string') {
                csv = xhr.responseText;
            }

            // parse the CSV trades
            var header, comment = /^#/, x;

            $.each(csv.split('\n'), function(i, line){
                if (!comment.test(line)) {
                    if (!header) {
                        header = line;
                    }
                    else {
                        var point = line.split(';'),
                            date = point[0].split('-'),
                            time = point[1].split(':');

                        if (point.length > 1) {
                            x = Date.UTC(date[2], date[1] - 1, date[0], time[2], time[1], time[0]);

                            array_holder.push([
                                x, // time
                                parseFloat(point[2]) // close
                            ]);
                        }
                    }
                }

            }); // each
            alert('No. 1' + array_holder[0]);
        });
        return array_holder;
    }

在下面的代码部分中,我试图调用getCsv,但未得到2号未定义

In the following section of code, I'm trying to call getCsv but I get No. 2 undefined

$(function() {

        var trades  = getCsv('trades.csv');
        var spreads = getCsv('spreads.csv');
        alert('No. 2' + trades[0]);
}

为什么我的数组没有填充?在实际的代码中,我具有上述两个功能,它们按此处列出的顺序彼此相邻.因此,可以正确读取文件,就好像array_holder超出范围并被垃圾回收一样.

Why are my arrays not getting populated? In the actual code I have the above two functions right next to each other in the order listed here. So the files are getting read correctly it's as if array_holder falls out of scope and gets garbage collected.

推荐答案

这是由于$.get()的异步特性引起的.在您发出警报的时候,AJAX请求不一定已经运行.

This is due to the asynchronous nature of $.get(). At the point where you do the alert, the AJAX request has not necessarily run yet.

在请求的成功回调中执行警报,该警报发生在"No.1"警报处.

Do the alerting in the request's success callback, where the "No.1" alert takes place.

这篇关于为什么我的JavaScript函数没有填充数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆