在条件语句不起作用的情况下运行for循环

时间:2019-08-14 13:15:22

标签: javascript

我使用ECMAScript筛选出一系列年份,以查找介于另一组年份之间的两年范围内的动物。

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

我使用jQuery使用两个$ .each,一个用于迭代多年,另一个嵌套的$ .each,用于比较当年和动物年份。

**我在代码中的注释显然已被删除。预期的结果是要显示每只动物,但是如果它们的动物日期在动物年的范围内,则显示动物日期,并表明它在两年之间。

我提供的名为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>

1 个答案:

答案 0 :(得分:0)

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

逻辑:

  • 创建了一个功能,该功能循环遍历array个对象(具有animaldatetitle属性的对象)。
  • 该函数根据您描述的逻辑构造一个HTML字符串,然后将其返回以便分配给innerHTML元素({{1} })。
  • 在遍历动物(基本上是HTML)时,将每个动物(动物)与所有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);