【问题标题】:Why does assigning an array element not work in this case?为什么在这种情况下分配数组元素不起作用?
【发布时间】:2021-06-05 18:53:02
【问题描述】:

我正在用 Javascript 制作一个函数来翻转字符串的字母。我正在使用多指针技术接近它。

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

但是由于某种原因,这种交换机制没有正确地将头部分配给尾部,将尾部分配给头部。运行该函数时,我只是返回原始字符串,这意味着交换机制中的分配不起作用。任何人都知道我可能做错了什么。

【问题讨论】:

  • Javascript 字符串是不可变的。
  • 字符串不是数组。
  • 字符串是不可变的。您不能使用 var myString = "abbdef"; 之类的方式更改字符串中的字符。我的字符串 [2] = 'c'。 trim、slice 等字符串操作方法返回新字符串。

标签: javascript arrays list


【解决方案1】:

JS 字符串(在 Java 中也是如此)是不可变的。

但是你没有收到关于它的警告

例如这段代码

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

我知道的最短的 JS 反向字符串代码(Dimitri L 建议是here

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

[...s] 将字符串拆分为字符数组。数组有.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
};

【讨论】:

    猜你喜欢
    • 2014-12-13
    • 2017-11-26
    • 2010-12-29
    • 1970-01-01
    • 2021-08-05
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多