简体   繁体   English

反向数组功能在javascript中不起作用

[英]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]);

Use push function instead of += . 使用push功能代替+=

 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])); 

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])) 

Also you can use more compact version of your code 您也可以使用更紧凑的代码版本

 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.

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