在node.js中未定义读取属性错误

Getting read property error undefined in node.js

本文关键字:读取 属性 错误 未定义 node js      更新时间:2023-09-26

我正在抓取部分,我正在很好地获取数据,但是当我迭代数组并试图获得数据扔给我时TypeError: Cannot read property '3' of undefined

我的代码是:
  $('table#blob1 tr.insRow').filter(function(){
            var data = $(this);
            i = i + 1;
            bow_arr[i] = new Array(6);
            bow_arr[i][1] = data.children(1).text();
            bow_arr[i][2] = data.children(2).text();
            bow_arr[i][3] = data.children(3).text();
            bow_arr[i][4] = data.children(4).text();
            bow_arr[i][5] = data.children(5).text();
            bow_arr[i][6] = data.children(6).text();    
   })

这里我正在创建二维数组并将数据插入其中。我能够正确地获取所有子元素的值并且我已经将所有这些数据插入到二维数组中。

过滤器函数运行了5次,因为它遇到了5次。

 for(i=0;i<1;i++){
     console.log(bow_arr[i][3]+" - "+bow_arr[i][4]);
  }

上面的代码,我只是试图打印值,但我得到TypeError这样。TypeError: Cannot read property '3' of undefined

根据你的代码,你的迭代器循环是用错误的方式编写的。

在你的代码中有

i = i + 1;

使你的数组看起来像这样:

bow_arr[0] === undefined; // equals true
bow_arr[1] === [ 'text from child 1', 'text from child 2' ... ]
bow_arr[2] === [ 'text from child 1', 'text from child 2' ... ]

和迭代器

for(i=0;i<1;i++) { ... }

将只迭代0一次。

你有两种可能。修改代码或修改迭代器

我选择修复你的迭代器,它应该看起来像:

for(i=1;i<bow_arr.length;i++){
   console.log(bow_arr[i][3]+" - "+bow_arr[i][4]);
}

只是为了确保您还可以包含一个检查,以查看数组中的此项是否未定义。

for(i=1;i<bow_arr.length;i++) {
   if ( !bow_arr[i] || !bow_arr[i][3] || !bow_arr[i][4] ) continue;
   console.log(bow_arr[i][3]+" - "+bow_arr[i][4]);
}

正如VisioN所说,您的索引为0,但您没有在该帖子中输入任何内容。将i初始化为0,应该没问题:)。将增量移动到过滤器函数的末尾

  var i = 0;
  $('table#blob1 tr.insRow').filter(function(){
            var data = $(this);
            bow_arr[i] = new Array(6);
            bow_arr[i][1] = data.children(1).text();
            bow_arr[i][2] = data.children(2).text();
            bow_arr[i][3] = data.children(3).text();
            bow_arr[i][4] = data.children(4).text();
            bow_arr[i][5] = data.children(5).text();
            bow_arr[i][6] = data.children(6).text();    
            i = i + 1;
   })

供参考:你在下面的代码中循环一次=有一个循环的意义是什么?:)

 for(i=0;i<1;i++){
     console.log(bow_arr[i][3]+" - "+bow_arr[i][4]);
  }