[英]reverse array function doesn't work in javascript
I want to reverse an array without using the built-in methods but the following function is not working: 我想在不使用内置方法的情况下反转数组,但是以下功能不起作用:
function reverseArray(arr) {
let brandNewArray = [];
for (let i = arr.length - 1; i >= 0; i--) {
brandNewArray += arr[i];
}
return brandNewArray;
}
reverseArray([1,2,3]);
Instead of +=
you need to push items into it. 而不是
+=
您需要将项目推入其中。 Using +=
at first time will assign to the brandNewArray
a string, (as [] + 1
will give you "1"
), with value of the last item. 第一次使用
+=
将为brandNewArray
分配一个字符串(如[] + 1
将为您提供"1"
),并带有最后一项的值。 Then string concatenation goes and you got 321
as the final value of brandNewArray
instead of array. 然后进行字符串串联,您得到
321
作为brandNewArray
的最终值而不是数组。
function reverseArray(arr) { let brandNewArray = []; for (let i = arr.length - 1; i >= 0; i--) { brandNewArray.push(arr[i]); } return brandNewArray; } console.log(reverseArray([1,2,3]))
const reverseArray = arr => arr.reduce((acc, cur) => (acc.unshift(cur), acc), []); console.log(reverseArray([1,2,3]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.