【问题标题】:Running for loop with conditional statements with map not working使用条件语句运行 for 循环,地图不起作用
【发布时间】:2019-12-21 01:25:14
【问题描述】:

我有一系列年份,我正在使用 ECMAScript 进行过滤,以从另一个年份数组中找到介于两年之间范围内的动物的匹配项。

我在回调中调用 buildList(animal) 的 for 循环不起作用,因为它每年都在迭代并忽略我在 for 循环中放置的条件。

我使用 jQuery 使用了两个 $.each,一个用于遍历年份,一个嵌套的 $.each 用于将当前年份与动物年份进行比较。

** 我在代码中的 cmets 显然被剥离了。预期结果是显示每只动物,但如果它们的动物日期在动物年范围内,则显示动物日期并显示它介于两年之间。

我提供的名为 buildList_example() 的示例函数演示了预期的结果,但在动物年的条件下使用了硬编码迭代器[0]

// array of years
let animalyears = ['1970', '1980', '1990', '2000', '2001']

// static data
let data = {
  "animals": [{
      "animaldate": "1972",
      "title": "Sparky"
    },
    {
      "animaldate": "1975",
      "title": "Max"
    },
    {
      "animaldate": "1980",
      "title": "Fido"
    },
    {
      "animaldate": "1981",
      "title": "Frank"
    },
    {
      "animaldate": "1994",
      "title": "Fiona"
    }
  ]
}


var allAnimals = data.animals;

var animalList
allAnimals.map((animal) => buildList(animal))

function buildList(animal) {
  for (var i = 0; i < animalyears.length; i++) {
    animalList += `<div class="animal">`
    if (animal.animaldate >= animalyears[i] && animal.animaldate < animalyears[i + 1]) {
      animalList += `<h1> ${animal.animaldate} </h1>`
      animalList += `<p> ${animal.title} </p>`
      animalList += `<p> Falls between ${animalyears[i]} and  ${animalyears[i + 1]}</p>`
    } else {
      animalList += `<p> ${animal.animaldate} </p>`
      animalList += `<p> ${animal.title} </p>`
    }
    animalList += `</div>`
  }

}


function buildList_example(animal) {
  animalList += `<div class="animal">`
  if (animal.animaldate >= animalyears[0] && animal.animaldate < animalyears[0 + 1]) {
    animalList += `<h1> ${animal.animaldate} </h1>`
    animalList += `<p> ${animal.title} </p>`
    animalList += `<p> Falls between ${animalyears[0]} and  ${animalyears[0 + 1]}</p>`
  } else {
    animalList += `<p> ${animal.animaldate} </p>`
    animalList += `<p> ${animal.title} </p>`
  }
  animalList += `</div>`
}

var output = document.getElementById("output")

output.innerHTML = animalList
.animal {
  border: 1px solid black;
  display: flex;
  flex-flow: column;
}
<div id="output">

</div>

【问题讨论】:

  • 错误似乎与问题无关。
  • 循环是否应该为年份和动物的每个组合添加一个&lt;div class="animal"&gt;?因为这就是它现在所做的。它根本没有忽略条件,但您的条件仅决定循环是否添加div, p, pdiv, h1, p, p。它不会跳过不属于年份范围的动物。
  • 不,我刚刚发现我的 cmets 在我添加它们并在帖子顶部进行说明时被删除了。调用 buildList_example() 会显示所需的结果,但它使用的是硬编码的迭代器,当我在函数内添加一个 for 循环时,我得到“未定义”返回,因此出现了问题。
  • 嗯。似乎很奇怪。无论如何,可能是这样的? jsfiddle.net/khrismuc/90kjw6tz

标签: javascript


【解决方案1】:

首先,此任务不需要jQuery,因为它可以使用forEach 方法完成(因为map 返回一个不能直接用作HTML 的数组分配给innerHTML 属性)。

逻辑:

  • 创建了一个函数,该函数循环遍历对象的array(具有animaldatetitle 属性的对象)。
  • 该函数根据您描述的逻辑构造一个HTML 字符串,然后将其返回以分配给HTML 元素的innerHTML(在我们的例子中为div#output)。李>
  • 在遍历动物(基本上是data.animals)时,将每一个(动物)与所有animalyears 元素进行比较。

不再赘述,这里有一个演示,说明了所说的内容:

const animalyears = ["1970", "1980", "1990", "2000", "2001"],
  data = {
    animals: [{
        animaldate: "1972",
        title: "Sparky"
      },
      {
        animaldate: "1975",
        title: "Max"
      },
      {
        animaldate: "1980",
        title: "Fido"
      },
      {
        animaldate: "1981",
        title: "Frank"
      },
      {
        animaldate: "1994",
        title: "Fiona"
      }
    ]
  },
  output = document.getElementById('output'),
  /** the filtering function
  * @param arr the animal array to be filtered.
  **/
  filterAnimals = arr => {
    /** the html that is going to be constructed **/
    let html = '';
    /** begining by looping through the "arr"
    * @param item the current element in the loop (from "arr").
    **/
    arr.forEach(item => {
      html += `<div class="animal"><h1>${item.animaldate}</h1>`;
      /** for every animal loop compare it to all the "animalyears" array's values 
      * @param y the current year from "animalyears".
      * @param i its index in the "animalyears" array.
      **/
      animalyears.forEach((y, i) => {
        html += `<p>${item.title}</p><p>`;
        /** while checking we ensure to check if we have an element at the index "i + 1" to prevent errors **/
        /** also the "+" sign used in front some variables is used to cast the strings into integers just to besure we compare real numbers not strings **/
        html += +item.animaldate >= +y && animalyears[i + 1] && +item.animaldate < +animalyears[i + 1] ? `Falls between ${y} and  ${animalyears[i + 1]}` : `${item.animaldate}`;
        html += `</p>`;
      });
      html += `</div>`;
    });
    /** return the constructed html **/
    return html;
  };

/** use the function **/
output.innerHTML = filterAnimals(data.animals);
.animal {
  border: 1px solid black;
  margin-top: 10px;
  padding: 0 8px;
}
&lt;div id="output"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2018-10-19
    • 2021-05-04
    • 2021-10-01
    相关资源
    最近更新 更多