简体   繁体   English

如何创建反向数组 function?

[英]How to create a reverse array function?

I am trying to write a function, reverseArray(), that takes in an array as an argument and returns a new array with the elements in the reverse order ( without using the built-in method ).我正在尝试编写一个 function, reverseArray(),它将一个数组作为参数并返回一个新数组,其中的元素以相反的顺序(不使用内置方法)。

Can someone help me to see what I'm doing wrong here?有人可以帮我看看我在这里做错了什么吗? It returns 1 when I ran the code below.当我运行下面的代码时它返回 1。

 const reverseArray=array=> { let newArray=[]; for (let i=array.length-1; i>=0; i--){ return newArray.push(array[i])} }; const array = ['sense.','make', 'all', 'will', 'This']; console.log(reverseArray(array));

You're returning the results of Array.push() on the first instance of the loop.您将在循环的第一个实例上返回Array.push()的结果。 According to MDN, Array.push() returns:根据 MDN, Array.push()返回:

The new length property of the object upon which the method was called.调用该方法的 object 的新长度属性。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

So it's pushing one element to the array, and returning the length of the array (1).所以它将一个元素推入数组,并返回数组的长度 (1)。

Instead, add all the elements to the array in the for loop, then return the array itself:相反,在 for 循环中将所有元素添加到数组中,然后返回数组本身:

 const reverseArray = arr => { let newArr=[] for (let i=arr.length-1; i>=0; i--){ newArr.push(arr[i]) } return newArr } const arr = ['sense.','make', 'all', 'will', 'This'] console.log(reverseArray(arr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM