簡體   English   中英

為什么在這種情況下分配數組元素不起作用?

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

我正在 Javascript 中制作 function 來翻轉字符串的字母。 我正在使用多指針技術來處理它。

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;
};

但是由於某種原因,這種交換機制沒有正確地將頭部分配給尾部,將尾部分配給頭部。 運行 function 時,我只返回原始字符串,這意味着交換機制中的分配不起作用。 任何人都知道我可能做錯了什么。

JS 字符串(也在 Java 中)是不可變的。

但是,您不會收到有關它的警告

例如這段代碼

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

我知道的最短的 JS 反向字符串代碼(如 Dimitri L 建議的在這里

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

[...s]將字符串拆分為字符數組。 Arrays 有.reverse()方法,然后join()將反向數組連接成一個新字符串。

您還可以重寫代碼以將字符串轉換為數組並在最后加入:

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
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM