将数据保存到二维数组的 JavaScript 代码抛出未定义的异常

标签 javascript html arrays web-scraping

我正在编写一个脚本,它从 html 表中获取值,在数组中对它们进行索引,然后将每个值分配给表单中的标记。Codepen https://codepen.io/anon/pen/eVLKyB

我的问题是,从数组中获取所有指定值后,我得到 enter image description here

负责从表中索引值的代码如下所示:

   function size_index(){
        var table = document.getElementsByClassName("product_table_cus");
        var index= [[],[]];
        var i_index = 0;
        var iter = 0; //index of first dim of array
        var len = table[0].rows.length;
        console.log("Len:"+len);
        while(i_index<len) {
           //iterate trough rows




               console.log("second for, iter:"+ i_index);
               var col_inner = table[0].rows[i_index].cells[0].innerHTML; //size param
               var col_param = table[0].rows[i_index].cells[1].innerHTML;//size value
               var col_size = col_inner.substr(col_inner.indexOf(' ')+1);
                console.log("Rozmiar:"+ col_size+"  Wartość:"+col_param);
        //       index[1][0].push("col_size");
          //     index[i_index][1].push(col_param);
                if(col_inner.search("Rozmiar")!==-1)
                {
                  console.log("Inner wtf:"+col_inner+"Ite:"+iter);
                  index[iter].push(col_inner,col_param);
                  console.log("Index+:"+index[iter]);
                  console.log("Ind:"+col_inner+"Val:"+col_param);
                }
                else if(col_inner.search("Rozmiar")==-1){

                }
                iter++;



          //     col_param=0;
        //       col_size=0;
               //iterate through columns
               //columns would be accessed using the "col" variable assigned in the for loop


           //rows would be accessed using the "row" variable assigned in the for loop
           i_index++;

         }
         return index;
      }

最佳答案

您可以在控制台日志中看到它:

这行代码

console.log("内部wtf:"+col_inner+"项目:"+iter);

产生此输出

Inner wtf:Rozmiar XXLIte:2

您的 index 变量中恰好有两个值。 因此,当然,如果 iter 是一个大于 1 的值,则此行将导致错误:

索引[iter].push(col_inner,col_param);

index中有两个元素,因此index[2]将返回undefined

<小时/> 您的根本问题是 [[][]] 不是二维数组。它是一个包含两个数组的数组。

更安全的方法是:

var index= [];

然后,添加一个元素:

index[iter] = index[iter] || [];
index[iter].push(...);

关于将数据保存到二维数组的 JavaScript 代码抛出未定义的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968869/

相关文章:

java - 将两个最多 50 位的整数相加

c - C语言中如何分配不同类型的内存?

java - 为什么我收到 "bad operand types for binary operator"错误?

javascript - 如何通过条形图的字长设置域?

javascript - HTML 多个 onclick 事件在我想要的时候没有发生

javascript - nodejs 加密模块 privateEncrypt() 总是返回相同的结果

html - 在 XAMPP 中从本地主机访问 html 文件时显示空白页面

切换到中东语言时 HTML 字体太小

javascript - 在表中动态添加行

html - Firefox 在 css 边距填充中显示奇怪的行为不起作用