简体   繁体   中英

Why does assigning an array element not work in this case?

I am making a function in Javascript to flip the letters of a string. I am approaching it using a multiple pointer technique.

const reverseString = (string) => {
  // Start at the front and swap it with the back
  // Increment front decrement back
  // Do this until we get to the center

  let head = string.length - 1;
  let tail = 0;
  let result = string;
  console.log(result);

  while (tail < head) {
    // Swap
    var temp = result[head];
    result[head] = result[tail];
    result[tail] = temp;

    tail++;
    head--;
  }
  return result;
};

But for some reason this swapping mechanism is not correctly assigning the head to the tail and the tail to the head. When running the function I just get the original string back return meaning that the assignment in the swapping mechanism isn't working. Anyone have any clue what I could be doing wrong.

JS strings (also in Java) are immutable.

However you do not get warnings about it

For example this code

const str = "abc";
str[0] = "z"; // does nothing, does not throw error or warn you
// str === "abc"

The shortest JS reverse string code I know (as suggested by Dimitri L is here )

function reverse(s){
    return [...s].reverse().join("");
}

[...s] splits string into array of characters. Arrays have .reverse() method and then join() joins reversed array into a new string.

You can also rewrite your code to convert string to array and join at the end:

const reverseString = (string) => {
    // Start at the front and swap it with the back
    // Increment front decrement back
    // Do this until we get to the center
    const charsArray = [...string]; // convert string to array of characters

    let head = charsArray.length - 1;
    let tail = 0;

    while (tail < head) {
        // Swap
        const temp = charsArray[head];
        charsArray[head] = charsArray[tail];
        charsArray[tail] = temp;

        tail++;
        head--;
    }
    return charsArray.join(''); // join reversed array
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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