【问题标题】:Javascript for loop stops before the end [duplicate]Javascript for循环在结束前停止[重复]
【发布时间】:2019-05-27 07:38:12
【问题描述】:

我有一个非常简单的自制 API,它可以读取服务器上一些文件的内容,解析它们并以 JSON 格式发送它们的内容。

我的网页使用 Ajax 调用 API,读取数据并将它们存储在自定义对象中。问题是,无论我在 JSON 中解析了多少文件,只有第一个文件被处理为我的 Javascript 代码。

runs = [];

function Solution(values) {
    this.number = values[0]
    this.weight = values[1]
    this.value = values[2]
    this.score = values[3]
}

function DateValue(date) {
    regex = new RegExp(/(\d{4})-(\d{1,2})-(\d{1,2})-(\d{1,2}):(\d{1,2}):(\d{1,2})-(\d{1,2})/)
    dateArray = date.split(regex)
    this.year = dateArray[1]
    this.month = dateArray[2]
    this.day = dateArray[3]
    this.hour = dateArray[4]
    this.minutes = dateArray[5]
    this.secondes = dateArray[6]
}           

function Run(values) {
    this.algorithm = values["log"]["Algorithm used"]
    this.weight = values["log"]["Weight"]
    this.value = values["log"]["Value"]
    this.date = new DateValue(values["log"]["Date"])
    this.solutions = []
    for(i = 0; i < values["datas"].length; i++) {
        this.solutions.push(new Solution(values["datas"][i]))
    }
}

$.ajax({
    url: 'api.php', // the data sent by the API is a valid JSON
    dataType: 'json',
    success: function(data, status) {
        console.log(data);
        for(i = 0; i < data.length; i++) {
            console.log(data[i]);
            var run = new Run(data[i])
            runs.push(run);
        }
    }
});

for 循环之前的console.log(data) 正确打印从 API 接收的所有数据,但 console.log(data[i]) 仅打印数组的第一个元素,我不明白为什么。

【问题讨论】:

  • TLDR:始终声明变量。
  • 在您的 javascript 文件顶部添加"use strict",以打开strict mode,这样当您在使用之前没有声明变量时会出现错误。在 for 语句中,您可以使用 let 代替 varfor (let i=0; i &lt; 10; ++i) { console.log(i); } 将变量的范围保持在 for 语句中。

标签: javascript ajax for-loop


【解决方案1】:

您在多个位置使用单个全局索引变量i 进行循环。

您的第一个循环调用Run,它运行另一个循环以完成递增i 变量。

开始你的循环,每次都声明一个本地 i

for(var i=0;...)

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多