【问题标题】:'Undefined Is Not A Function' while using arrays in NodeJS在 NodeJS 中使用数组时“未定义不是函数”
【发布时间】:2015-08-13 11:12:10
【问题描述】:

我正在用cheerio 运行节点。我有这个函数需要显示数组中包含的元素的属性值。

for (var row = 0; row < array.length; row++) {
    console.log("Row Length: " + array[row].length);
    for (var col = 0; col < array[row].length; col++) {
        console.log("Inside:");
        console.log(array[row][col].getAttribute('val'));        
    }
}

我的数组包含使用 push 填充的列表项

array.push($('[title!="CATA"][collection="items"]'));

我得到了“行长度”的所需输出,它显示“内部”,但随后显示“类型错误:未定义不是函数”。我也尝试过使用 .attr('val') 但同样的错误。

执行 console.log(array[row][col]) 给我以下。

{ type: 'tag',
  name: 'li',
  attribs: 
   { id: 'Amber',
     collection: 'items',
     title: 'disk',
     val: '10|9|2|10|7|13|2|10|12|2|2|5|3|3|5|2|8|7|5|10|4|6|6|3|4|6|2|8|11|2|10|7|9|9|10|8' },
  children: 
   [ { data: 'disk : 10|9|2|10|7|13|2|10|12|2|2|5|3|3|5|2|8|7|5|10|4|6|6|3|4|6|2|8|11|2|10|7|9|9|10|8',
       type: 'text',
       next: null,
       prev: null,
       parent: [Circular] } ],
  next: 
   { type: 'tag',
     name: 'li',
     attribs: 
      { id: 'Amber',
        collection: 'items',
        title: 'usb',
        val: '3|3|2|4|2|4|3|3|3|13|5|13|2|13|2|5|5|3|4|3|6|3|2|2|5|13|2|3|2|13|2|13|2|2|13|4' },
     children: [ [Object] ],
     next: 
     .
     .
     .

我要做的就是访问“val”。

【问题讨论】:

  • 你打印了 array[0][0] 元素吗?您正在研究 HTML 元素,但我怀疑数组没有在数组 [0][0] 索引处保存 HTML 元素。

标签: javascript arrays node.js cheerio


【解决方案1】:

我认为,错误是由这一行产生的

console.log(array[row][col].getAttribute('val'));

您正在对非对象调用 .getAttribute。提供完整列表。

【讨论】:

  • 感谢您的建议。我正在尝试让 JQuery 代码在带有cheerio 的节点上工作。我知道cheerio 和 JQuery 是不同的,但我需要一些帮助来访问存储在数组中的元素的属性。
  • @NeelDeveloper 您将不得不提供一些示例 HTML 代码以及您希望选择器实际挑选出的内容(如果这是您正在寻找的帮助)。
【解决方案2】:

已解决:

console.log(array[row][col].attribs.val);

【讨论】:

    【解决方案3】:

    您的数组中的一个或多个值是undefined,当您在其上调用getAttribute 时,会抛出错误TypeError: undefined is not a function。要对此进行调试,请使用console.log(array) 或使用调试器查看数组内的数据。最终,jQuery 函数将使用未分配的变量填充数组,因此请查看选择器并查看它是否符合您的预期。

    【讨论】:

      【解决方案4】:

      首先,打印一条更有用的消息:

      if (!array[row][col] || !(array[row][col].getAttribute)) {
          console.log(row, col, array[row][col]);
      }
      

      现在在您的控制台上查看,您会看到数组中未填充您期望的对象种类的索引,以及那些对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        • 2015-09-29
        相关资源
        最近更新 更多