【问题标题】:How to count downwards with forEach loop javascript如何使用 forEach 循环 javascript 向下计数
【发布时间】:2021-10-19 15:31:25
【问题描述】:

所以我想浏览一个对象列表,但我无法索引它,但可以使用 forEach 浏览元素...我的问题是我需要从最后一个对象转到第一个但不知道该怎么做使用 forEach 函数!如果我做一个 for 循环,它看起来像这样:

var test = [1,2,3,4,5]
   for (let i = test.length; i > -1; i=i-1) {
       console.log(test[i])
   }

但正如我解释的那样,我无法索引它。那你能帮帮我吗?

【问题讨论】:

    标签: javascript arrays loops for-loop foreach


    【解决方案1】:

    你可以reverse()循环前的数组:

    var test = [1,2,3,4,5]
     
    test.reverse().forEach(e => console.log(e));

    【讨论】:

      【解决方案2】:

      这里是你的问题的代码:

      var test = [1, 2, 3, 4, 5]
          for (let i = test.length - 1; i >= 0; i--) {
            console.log(test[i])
          } 

      【讨论】:

        【解决方案3】:

        这是 Severin.Hersche 方法的一种变体:

        const test = [1, 2, 3, 4, 5];
        for (let i = test.length;i--;) console.log(test[i]);

        【讨论】:

          【解决方案4】:

          请使用此代码。

          var test = [1,2,3,4,5]
          test.forEach((val, index) => console.log(test[test.length - index - 1]));

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-07-21
            • 2020-07-31
            • 1970-01-01
            • 1970-01-01
            • 2021-05-30
            • 2019-01-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多