交换数组和反向

Exchange Array and Reverse

输入:[2,4,5],['a','b','c'] 输出:['c'、'b'、'a']、[5,4,2]

function exchangeWith(a,b){
    [a,b] = [b,a].forEach(e  => e = e.reverse() )
}

我得到这个错误:undefined is not iterable (cannot read 属性 Symbol(Symbol.iterator))

错误:

undefined is not iterable (cannot read property Symbol(Symbol.iterator)

是由于:

[a,b] = [b,a].forEach(/* ... */)

forEach 总是 returns undefined 并且:

[a,b] = undefined

会引发错误,因为 undefined 不可迭代。

此解决方案基于这样一种假设,即您一次提供一个不同的数组,而不是数组的数组。如果您输入的是数组数组,请告诉我,我会根据此更改解决方案。

您可以为此使用 lodash 库。

const updatedArray = _.reverse(array);

示例如下:

let array = [1,2,3];
let array2 = ["c","d","a"];

const test = (array, index) => {
  document.getElementById("input" + index).innerHTML = array.join(", ");
  const updatedArray = _.reverse(array);
  document.getElementById("output" + index).innerHTML = updatedArray.join(", ");
};

test(array, 1);
test(array2, 2);
<html>
  <head>
  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
  </head>
  <body>
    <p>Input: <span id="input1"></span></p>
    <p>Output: <span id="output1"></span></p>
    <br/>
    <p>Input: <span id="input2"></span></p>
    <p>Output: <span id="output2"></span></p>
  </body>
</html>