JS:反转数组但只反转原始数组 -->错误:无输出运行 [英] JS: Reverse an Array but Reverse the Original Array Only --> Error: running with no output

查看:31
本文介绍了JS:反转数组但只反转原始数组 -->错误:无输出运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

//反向数组

编写一个函数,该函数接受一个数组并原地反转该数组.该行为应该模仿本机 .reverse() 数组方法的行为.但是,您的反向函数应该接受要操作的数组作为参数,而不是作为该数组上的方法调用.

Write a function that accepts an array and reverses that array in place. The behavior should mimic the behavior of the native .reverse() array method. However, your reverse function should accept the array to operate on as an argument, rather than being invoked as a method on that array.

不要在您自己的实现中使用原生的 .reverse() 方法.

Do not use the native .reverse() method in your own implementation.

我尝试了以下代码:

let myArray = [1, 2, 3, 4];


function reverse(myArray) {

  let newArray = []; 

  // pop all of elements from roginal array, and store in new array

  for (i=myArray.length-1; i>=0; i--){
    newArray.push(myArray[i])

    console.log(newArray)
  }

  while (newArray.length){

    myArray.unshift(newArray)
  }


  return myArray; 
}


reverse(myArray);
console.log(myArray) // expected output is [4, 3, 2, 1]

我的代码一直在运行,没有产生 console.log 输出.请注意,我希望对输入数组参数进行反向操作.

My code just keeps running and no console.log output is produced. Notice I want the reverse done to the input array argument.

我做错了什么?另外,while (newArray.length) 是什么意思/它在概念上是做什么的?

What am I doing wrong? Also, what does while (newArray.length) mean / what is it doing conceptually?

推荐答案

不知道为什么你需要 unshift 你可以迭代并返回你推送值的数组

Not sure why you need the unshift you can just iterate and return the array where you are pushing the value

let myArray = [1, 2, 3, 4];

function reverse(myArray) {
  let newArray = [];
  for (i = myArray.length - 1; i >= 0; i--) {
    newArray.push(myArray[i])
  }
  return newArray;
}
console.log(reverse(myArray))

这篇关于JS:反转数组但只反转原始数组 -->错误:无输出运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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