簡體   English   中英

在Promise.then()中的for循環后變量不可用

[英]variable not available after for-loop inside Promise.then()

我在Promise.then()中使用包含if語句的for循環(它是一個api調用)。 在for循環之前初始化的變量在for循環中可用,但不在之后。

我在for循環之前,在for循環內部,if語句內部,if語句之后,以及for循環之后控制記錄變量。 最后一個console.log甚至沒有定義。 它似乎根本沒有注冊。

我在Chrome控制台中嘗試了相同基本結構的簡單版本,但它的工作原理不同,但不同之處在於Chrome控制台中我不在Promise.then()中。 所以我認為我不了解它。

$(document).ready(function() {
  const url = 'https://www.ndbc.noaa.gov/data/realtime2/46029.spec';
  const newBouyData = new BouyData();

  let currentBouyData = newBouyData.getBouyData(url);
  currentBouyData.then((text) => {
    const today = new Date();
    let lineDate;
    let line;
    let lineArray;
    const lines = text.split('\n');
    let currentData;

    for (let i = 2; i <= lines.length; i++) {
      line = lines[i];
      lineArray = line.split(' ');
      lineDate = new Date(lineArray[0], lineArray[1] - 1, lineArray[2]).toLocaleDateString();

      if ( today.toLocaleDateString() === lineDate && today.getHours() === parseInt(lineArray[3]) ) {
        currentData = lineArray;
      }
    }
    console.log('currentData after: ', currentData);
. . .

我期待currentData是一個字符串數組。 我一無所獲。 甚至不是console.log。

我錯過了什么?

謝謝你的想法。

for (let i = 2; i <= lines.length; i++) {
  line = lines[i];
  lineArray = line.split(' ');
  ...
}
console.log('currentData after: ', currentData);

數組arr的有效索引是從0arr.length - 1

你的循環條件是i <= lines.length ,這意味着在最后一次迭代中i的值為lines.length 然后, lines[i]訪問數組邊界之外的元素,產生undefined

lineArray = line.split(' ')然后拋出異常,因為undefined不是對象而undefined.split是一個錯誤。

這就是為什么循環之后的代碼永遠不會執行的原因。

試試i < lines.length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM