【问题标题】:How to start item index with 1如何以 1 开始项目索引
【发布时间】:2021-03-31 07:30:38
【问题描述】:

我正在遍历数组“fruits”。我希望它的索引从 1 开始。但输出从 0 开始。 这是我的代码

var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}

这是输出。

0:apple
1:orange
2:cherry

如何让它从 1 开始?

【问题讨论】:

  • 试试var fruits = [null,"apple", "orange", "cherry"];
  • forEach 从0开始索引,需要在innerHTML中手动增加索引值。 (index+1) + ":" + ...
  • “我如何让它以 0 开头?” - 它已经做到了?
  • 所以加一个??????

标签: javascript node.js reactjs foreach


【解决方案1】:

手动给索引加1:

(index + 1)

var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

function myFunction(item, index) {
    document.getElementById("demo").innerHTML += (index + 1) + ":" + item + "<br>";
}
&lt;div id='demo'&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:
    function myFunction(item, index) {
        var index2 = index + 1;
        document.getElementById("demo").innerHTML += index2 + ":" + item + "<br>";
    }
    

    【讨论】:

      【解决方案3】:

      试试这个

      var fruits = ["apple", "orange", "cherry"];
      
      for (var i = 1; i < arr.length; i++) {
          myFunction(fruits[i], i);
      }
      
      function myFunction(item, index) {
      document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
      }
      

      【讨论】:

        【解决方案4】:

        只需对从您想要的元素开始的新数组使用 foreach 方法。您可以使用 slice 方法来做到这一点。

        fruits.slice(1).forEach(myFunction);
        

        您可以查看此链接以获取有关切片方法https://www.w3schools.com/jsref/jsref_slice_array.asp 的更多信息。

        【讨论】:

          猜你喜欢
          • 2022-12-17
          • 2020-08-09
          • 1970-01-01
          • 2013-01-01
          • 2023-03-30
          • 2011-11-06
          • 2016-12-27
          • 2019-12-20
          • 1970-01-01
          相关资源
          最近更新 更多