未定义时如何定义多维数组?

时间:2015-06-24 02:19:22

标签: javascript multidimensional-array

这是我的代码:

    if(notas_insert[selected_n_document] === "undefined"){
        notas_insert[selected_n_document] = [];
    }
    if(notas_insert[selected_n_document][selected_version] === "undefined"){
        notas_insert[selected_n_document][selected_version] = [];
    }
    if(notas_insert[selected_n_document][selected_version]["index"] === "undefined"){
    notas_insert[selected_n_document][selected_version]["index"] = 0;
    }
    notas_insert[selected_n_document][selected_version][notas_insert[selected_n_document][selected_version]["index"]] = notas_pre;
    notas_insert[selected_n_document][selected_version]["index"]++;

我收到此错误:

Cannot read property '1' of undefined

如何在包含代码的数组中创建数组,因为如果我在控制台中编写:

notas_insert[selected_n_document] = [];

我不再在第三行收到错误,但出于某种原因,如果我在代码中执行此操作似乎不起作用。

2 个答案:

答案 0 :(得分:1)

检查你的情况

if(typeof notas_insert[selected_n_document][selected_version] === "undefined")

答案 1 :(得分:0)

我设置的默认值如下:

var doc = notas_insert[selected_n_document] || [];
var version = doc[selected_version] || [];