为什么我不能在 javascript 字符串中交换字符? [英] Why can't I swap characters in a javascript string?

查看:28
本文介绍了为什么我不能在 javascript 字符串中交换字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试交换数组的第一个和最后一个字符.但是 javascript 不允许我交换.我不想使用任何内置函数.

I am trying to swap first and last characters of array.But javascript is not letting me swap. I don't want to use any built in function.

function swap(arr, first, last){
    var temp = arr[first];    
    arr[first] = arr[last];
    arr[last] = temp;
}

推荐答案

因为字符串是不可变的.

Because strings are immutable.

数组符号就是:一个符号,一个charAt方法的快捷方式.您可以使用它来按位置获取字符,但不能设置它们.

The array notation is just that: a notation, a shortcut of charAt method. You can use it to get characters by position, but not to set them.

因此,如果您想更改某些字符,则必须将字符串拆分为多个部分,并从中构建所需的新字符串:

So if you want to change some characters, you must split the string into parts, and build the desired new string from them:

function swapStr(str, first, last){
    return str.substr(0, first)
           + str[last]
           + str.substring(first+1, last)
           + str[first]
           + str.substr(last+1);
}

或者,您可以将字符串转换为数组:

Alternatively, you can convert the string to an array:

function swapStr(str, first, last){
    var arr = str.split('');
    swap(arr, first, last); // Your swap function
    return arr.join('');
}

这篇关于为什么我不能在 javascript 字符串中交换字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆