【问题标题】:Pushing an object to an array makes it undefined--Scoping issue?将对象推送到数组使其未定义 - 范围问题?
【发布时间】:2017-01-06 05:11:47
【问题描述】:

我正在编写一个网络爬虫,它使用正则表达式来提取段落中的信息并将其存储在一个对象中。然后我将对象添加到数组中。这是我的完整代码:

function scrapeCourseData(htmlString) {
  // scrapes a specific department's course list 

  var tempArr = [];

  console.log(tempArr); // outputs '[]' 

  $ = cheerio.load(htmlString);

  // #coursestextcontainer contains the actual information for every single course listed in a department                           
  $('#coursestextcontainer').find('.courseblock').each(function(i, elem) {
    // finds all divs of type courseblock, iterates though each of them,
    // extracting course information from children. 

    console.log('courseblock ' + (i + 1));

    var courseText = $('strong', '.courseblocktitle', elem).text(); // Gets the text that will be parsed 

    var regex = /([A-Z]{4}\s[A-Z]{1,2}\d{4})\s(.*?)(?:\.*)(\d{1,2}(?:\.?|-?)\d{0,2}\spoints?)/g;
    var regexGroups = Object.freeze({
      NUMBER: 1,
      NAME: 2,
      CREDITS: 3
    });

    var match, course;

    while ((match = regex.exec(courseText)) !== null) { // when regex.exec returns null, no more matches, and loop stops.
      course = {
        number: match[regexGroups.NUMBER],
        name: match[regexGroups.NAME],
        credits: match[regexGroups.CREDITS]
      };

      tempArr.push(course); // doesn't work-- result is array full of 'null'
      console.log(course); // but this outputs as a valid object, e.g. { number: 'AFAS W3030'... }
    }

  });

  console.log("Complete tempArr: " + tempArr); // outputs [object Object],[object Object],[object Object], etc. 

  for (var j of tempArr) {
    dataJSONObject.push(tempArr[j]);
    console.log('\ntempArray at ' + j + ': ' + tempArr[j]); // outputs [object Object]: undefined
  }

  console.log('\n');
}

当我第一次将tempArr 定义为[] 并将其输出到控制台时,我得到了预期的结果[]

我从正则表达式匹配形成的对象在运行时也如预期的那样有效。

但是,当我尝试将这些对象推送到tempArr,然后打印tempArr 时,它输出为undefined

我一直在探讨其他 stackoverflow 问题,我很确定我的问题是当我推送到 tempArr 时,我这样做超出了它的范围。我已经尝试在我声明tempArr 的地方移动(例如,通过将其置于其函数之外以使其成为全局),但在推送后我仍然得到undefined。我错过了什么?

【问题讨论】:

  • tempArray 是 JSON 而不是 console.log("Complete tempArr: " + tempArr); 试试 console.log("Complete tempArr: " + JSON.stringify(tempArr));
  • 我认为您需要手动设置 reg.lastIndex = 0; 。看thisthis

标签: javascript arrays object undefined push


【解决方案1】:

你推入数组的对象在那里,你只是错误地从数组中读出。 for...of 循环不会将索引值放入您提供的变量中,而是将 放入。这就解释了为什么tempArr[j]undefined

将您的 for...of 循环更改为:

for (var j of tempArr) {
    dataJSONObject.push(j);
    console.log('\ntempArray: ' + j);
}

另外,将一个数组的所有元素放入另一个数组的另一种方法是使用spread syntax

dataJSONObject.push(...tempArr);

【讨论】:

  • 成功了,谢谢!我唯一需要做的另一件事是在console.log() 中对j 值进行字符串化。 (我认为console.log({object}) 在传递的对象上隐式调用stringify(),但console.log('string' + {object}) 没有,因为连接后输入是string 而不是JSON。)
猜你喜欢
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多