javascript - "Undefined"作为赋值的结果

标签 javascript variable-assignment

我是 JavaScript 新手。面临以下问题

var list = [];

initList(); // after this function I have some elements in `list`

var node = list[0]; //after the assignment firebug says `node` is undefined. `list[0]` is defined and contains object like {a:"value",b:"value1", ...}

我做错了什么? 我试过像 var node = {}; 那样声明 node。但它也不起作用。

这是我的 initList 函数。希望会有人想要掌握它:))

function initList() {

    d3.json("./config.json", function (error, txt) {
        if (error) {
            console.debug(error)
        }
        txt.forEach(function (bop, i) {

            var nd = {};

            d3.json("./cgi-bin/getshmid.sh?key=" + (195951310 + bop.bop_id), function (error, shm) {
                if (error) {
                    console.debug(error)
                } else {
                    console.debug(bop, i)
                }


                d3.select("#tplace")
                    .append("h3")
                    .text("BOP's ID = " + bop.bop_id)

                var table = d3.select("#tplace")
                    .append("table")
                    .attr("id", "shmid_" + shm.id);

                var thead = table.append("tr")

                thead.append("td")
                    .text("Блоки детектирования, ID")
                thead.append("td")
                    .text("Текущее значение")
                thead.append("td")
                    .text("Предупредительная уставка")
                thead.append("td")
                    .text("Аварийная уставка")
                thead.append("td")
                    .text("Статус")
                thead.append("td")
                    .text("Превышение ПУ")
                thead.append("td")
                    .text("Превышение АУ")

                bop.BDs.forEach(function (bd, i) {
                    var tbody = table.append("tr")
                        .attr("class", "bd")
                    tbody.append("td")
                        .text(bd.index + 1)
                    tbody.append("td")
                        .attr("id", "val")
                    tbody.append("td")
                        .attr("id", "pz")
                        .attr("class", "edit " + (516 + i * 16) + "")
                    tbody.append("td")
                        .attr("id", "az")
                        .attr("class", "edit " + (518 + i * 16) + "")
                    tbody.append("td")
                        .attr("id", "status")
                    tbody.append("td")
                        .attr("id", "state_pz")
                    tbody.append("td")
                        .attr("id", "state_az")
                })

                nd = foo(shm.id);
                list.push(nd);
            })
        })
    })
};

function foo(id) {

    var node = {
        value: id,
        table: d3.select('#shmid_' + id),
        tr: d3.select('#shmid_' + id).selectAll(".bd"),
        bds: []
    };

    node.tr.each(function (d, i) {

        var bd = {};

        d3.select(this).selectAll("td").each(function (d, i) {

            switch (d3.select(this).attr("id")) {
                case 'val':
                    bd.val = d3.select(this);
                case 'pz':
                    bd.pz = d3.select(this);
                case 'az':
                    bd.az = d3.select(this);
                case 'status':
                    bd.status = d3.select(this);
                case 'state_pz':
                    bd.stpz = d3.select(this);
                case 'state_az':
                    bd.staz = d3.select(this);
            }
        });

        node.bds.push(bd);
    });

    return node;
};

最佳答案

根据问题,问题是 initList 是一个异步函数。所以数组 list 不会被初始化。

var list = [];
initList(); //WARNING: asynchronous function!!!
var node = list[0]; 

您应该开始了解 JavaScript Promises


这就是您的代码所发生的情况。第一行创建一个名为 list 的数组。第二行通过 ajax 调用初始化列表。但是在回调发生之前,第三行被执行,给你一个错误,因为你试图获取一个未填充数组的第一个元素。
更新:

我还没有试过,但是d3.promise plugin看起来很简单。

var promise = d3.promise.json('test.json')
promise.then(function (data) {
    // call successful
}, function (error) {
    //call failed
});

关于javascript - "Undefined"作为赋值的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32498298/

相关文章:

php - 在 php 中创建组合框时 Onchange 事件的语法

javascript - 图片在响应时从 BW 淡入颜色

c++ - 有什么区别 - const int x = 5000;和 const int x = 50'00;在 C++ 中?

python - 替换 numpy 矩阵中的列

C++11。是否可以这样做 : string foo = cout << (. 00000023)*(.00000023) << endl; -精确

javascript - 为什么不推荐 "$().ready(handler)"?

javascript - 为什么此链接在 iOS Safari 上不可点击?

python - 如何控制Tensorflow中的分配顺序?

javascript - 将数组从 android 传递到 JavaScript

PHP - 如何在 2 个 foreach 循环内为数组分配字符串键和值?