javascript反向数组而不使用reverse() [英] javascript reverse an array without using reverse()

查看:94
本文介绍了javascript反向数组而不使用reverse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用reverse()函数的情况下反转数组:

I want to reverse an array without using reverse() function like this:

function reverse(array){
    var output = [];
    for (var i = 0; i<= array.length; i++){
        output.push(array.pop());
    }

    return output;
}

console.log(reverse([1,2,3,4,5,6,7]));

然而,它显示[7,6,5,4]有人可以告诉我,为什么我的反转功能错了?提前致谢!

However, the it shows [7, 6, 5, 4] Can someone tell me, why my reverse function is wrong? Thanks in advance!

推荐答案

array.pop()从数组中删除弹出的元素,将其大小减小一个。一旦你在 i === 4 ,你的休息条件不再评估为 true 并且循环结束。

array.pop() removes the popped element from the array, reducing its size by one. Once you're at i === 4, your break condition no longer evaluates to true and the loop ends.

一种可能的解决方案:

function reverse(array) {
  var output = [];
  while (array.length) {
    output.push(array.pop());
  }

  return output;
}

console.log(reverse([1, 2, 3, 4, 5, 6, 7]));

这篇关于javascript反向数组而不使用reverse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆