尝试插入数组时未定义的推送

时间:2016-08-18 04:17:06

标签: javascript arrays

我是Javascript的新手,我想将我的文本文件中的所有数据推送到数组,它可以正常工作: -

var pokemon_array = [];
$.get('pokemonlist.txt', function(data) {
        var lines = data.split('\n');

        for(var i=0;i<lines.length;i++) {
            var arr = lines[i].split('"');

            pokemon_array.push(arr[1]);
            pokemon_array.push(arr[3]);
            pokemon_array.push(arr[4]);
        }
        console.log(pokemon_array);
    });

我希望它有2维数组,所以我把它放在: -

var pokemon_array = [];
$.get('pokemonlist.txt', function(data) {
        var lines = data.split('\n');

        for(var i=0;i<lines.length;i++) {
            var arr = lines[i].split('"');

            pokemon_id = arr[1];
            pokemon_img = arr[3];
            pokemon_name = arr[4];

            pokemon_array[i].push(pokemon_id);
            pokemon_array[i].push(pokemon_img);
            pokemon_array[i].push(pokemon_name);
        }
        console.log(pokemon_array);
    });

然后我收到了这个错误: -

Uncaught TypeError: Cannot read property 'push' of undefined

我在这里做错了什么?

3 个答案:

答案 0 :(得分:3)

更改

pokemon_array[i].push(pokemon_id);
pokemon_array[i].push(pokemon_img);
pokemon_array[i].push(pokemon_name);

pokemon_array.push([ pokemon_id, pokemon_img, pokemon_name ]);

否则pokemon_array[i]还没有。

另外,您最好使用pokemon_...声明var个变量,或者如果要将它们的唯一用途添加到数组中,则只需pokemon_array.push([ arr[1], arr[3], arr[4] ]);

答案 1 :(得分:0)

问题是pokemon_array[i]pokemon_array[0]pokemon_array[1]等从未被分配过。

您可以将代码更改为:

        pokemon_array[i] = [];
        pokemon_array[i].push(pokemon_id);
        pokemon_array[i].push(pokemon_img);
        pokemon_array[i].push(pokemon_name);

或者

pokemon_array[i] = [pokemon_id, pokemon_img, pokemon_name];

或者你可以把它写得更短,因为你可以使用你拥有的数组:

pokemon_array[i] = arr;

但你根本不需要[i],所以你可以这样:

pokemon_array.push([pokemon_id, pokemon_img, pokemon_name]);

如上所述可以更短:

pokemon_array.push(arr);

这不只是追加arr中的每个元素。它会将整个arr添加为pokemon_array的一个元素,正如您所希望的那样。

答案 2 :(得分:0)

您收到错误,因为pokemon_array [i]未定义

pokemon_array[i].push(pokemon_id);
pokemon_array[i].push(pokemon_img);
pokemon_array[i].push(pokemon_name);

pokemon_array.push(pokemon_id);
pokemon_array.push(pokemon_img);
pokemon_array.push(pokemon_name);