【发布时间】: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