繁体   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