【问题标题】:How to avoid the skipping of the array index in a second array?如何避免跳过第二个数组中的数组索引?
【发布时间】:2018-09-21 16:41:51
【问题描述】:

怎样才能不跳过当年的数组元素呢?

我希望结果是:

Banana
0
Mango
1

当前结果:

Banana
0
Mango
3

代码在这里:

<body>
<p id="demo"></p>
<script>
    var fruits, text, year, i;
    fruits = ["Banana", "Orange", "Apple", "Mango"];
    year = ["0", "1", "2", "3"];
    text = "<ul>";
    for (i = 0; i < fruits.length; i++) {
        switch (fruits[i]) {
            case 'Mango':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
            case 'Pine apple':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
            case 'Grape':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
            case 'Banana':
                text += "<li>" + fruits[i] + "</li>";
                text += "<li><b>" + year[i] + "</b></li>";
                break;
        }
    }
    text += "</ul>";
    document.getElementById("demo").innerHTML = text;
</script>

【问题讨论】:

  • 你能详细说明你的问题吗?我不明白您所说的“不跳过数组顺序”是什么意思

标签: javascript arrays loops switch-statement


【解决方案1】:

像你一样循环遍历数组,并在水果与其中一个 case 语句匹配时增加第二个计数器。使用计数器从数组中获取年份编号:

var fruits, text, year, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
year = ["0", "1", "2", "3"];
text = "<ul>";
let counter = 0; // <-- define a second counter
for (i = 0; i < fruits.length; i++) {
  switch (fruits[i]) {
    case 'Mango':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++; // <-- that only get's incremented when a case is matched
      break;
    case 'Pine apple':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++;
      break;
    case 'Grape':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++;
      break;
    case 'Banana':
      text += "<li>" + fruits[i] + "</li>";
      text += "<li><b>" + year[counter] + "</b></li>";
      counter++;
      break;
  }
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
&lt;p id="demo"&gt;&lt;/p&gt;

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2017-04-17
    • 2012-12-08
    • 2022-09-23
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    相关资源
    最近更新 更多