Reverse 和 Join 函数输出原始数组

Reverse and Join Functions Outputting Original Array

我有一个数组,我们将其命名为 arr 并为其赋值 [a, a, b, c, d]。我试图首先反转数组,然后将它连接在一起以生成一个字符串。当我执行代码时:

arr.reverse().join('');

我希望得到(减去引号)的输出:

'dcbaa'

然而,我实际得到的是:

'aabcd'

我是不是做错了什么?我只是不理解我正在编写的代码的核心功能吗? reverse函数是不是返回reverse然后一到join函数就扔掉?我的印象是反转字符串的一个好方法是使用:

str.split('').reverse().join('');

因为我已经有了阵列,所以我只使用它的最后一部分。如有任何帮助,我们将不胜感激。

编辑上下文: 我正在写一个函数来寻找回文。我取一个传递给函数的字符串,然后找到该字符串中最长的回文。

longestPalindrome=function(s){
  var strlen = 0;  
  var stringArr = s.toLowerCase().split('');
  var chunk = '';

  if(s.length === 0){
    return strlen;
  }

  //for loop to go through each letter
  for(var i = 0; i < s.length; i++){
    //for loop to grab increasing chunks of array (a, ab, abc, abcd, etc.)
    for(var j = 0; j < s.length - i; j++){
      //Grab piece of string and convert to array
      chunk = stringArr.slice(i, (s.length - j));
      //View new array
      console.log(chunk);
      //Reverse chunk for later comparison
      var chunkReverse = chunk.reverse();
      //Check to see what reverse of array would be
      console.log(chunkReverse);
      //Create string from chunk
      chunk = chunk.join('');
      //view string from former chunk array
      console.log(chunk);
      //Create string from reversed array
      chunkReverse = chunkReverse.join('');
      //View reversed string from chunk array
      console.log(chunkReverse);
    }
  }

  return strlen;
}

我从上面得到的输出给了我(来自原始 post 的虚拟数据):

[a,a,b,c,d]
[d,c,b,a,a]
aabcd
aabcd

我希望这有助于澄清。

reverse method mutates the original array and returns that array. To prevent that from happening, copy the original array before reversing it by using slice:

var chunkReverse = chunk.slice().reverse();

希望对您有所帮助。