为什么我不能在不事先将其转换为数组的情况下反转字符串

时间:2018-02-02 15:37:31

标签: javascript arrays string reverse

谁能告诉我为什么我不能这样做?我知道首先转换为数组,但为什么呢?谢谢!

function reverseString(s){
    if(s.length<2){return s}
    var i=0, j=s.length-1;
    while(i<j){
        var temp = s[i];
        s[i]=s[j];
        s[j]=temp;
        i++;
        j--;
    }
    return s
}

2 个答案:

答案 0 :(得分:1)

字符串是不可变的。你永远不能改变它们。

它们具有允许您读取单个字符的数字属性,但这些属性是只读的(如果您可以写入它们,则字符串不会是不可变的)。

答案 1 :(得分:-1)

您可以使用递归来反转字符串,而无需将字符串转换为数组。

此代码基本上将输入字符串中的最后一个字符切片并将其附加到累加器,它将继续调用自身,直到输入字符串不再具有将返回累加器字符串的任何字符。

作为奖励,它的尾部是递归的,所以在现代浏览器中你可以处理任何大小的字符串。

如上所述,字符串是不可变的,所以你不会得到你输入的相同的字符串,但你可能不需要担心。

const reverse= (xs, acc = '') =>
  !xs.length
    ? acc
    : reverse(
        xs.slice(0, -1), // get the start of the string
        acc.concat(xs.slice(-1)) // append the end of the string to the accumulator
      )
    
console.log(
  reverse('.gnirts rotalumucca eht nruter lliw ti erehw sretcarahc yna sah regnol on gnirts tupni eht litnu flesti gnillac eunitnoc lliw ti ,rotalumucca eht ot ti dneppa dna gnirts tupni eht morf retcarahc tsal eht ecils yllacisab lliw edoc sihT')
)

console.log(
  // you can even use it on an array if you change the accumulator to an array
  reverse(['one', 'two', 'three'], [])
)

console.log(
  // or you could put it into an array
  reverse('reverse', [])
)