JavaScript 数组映射函数不会更改字符串中的元素吗?



所以我尝试使用 map() 方法,如下所示:

words = ["One", "Two"];
words = words.map(function(currentValue)
    {
        alert(currentValue[0]);//Output: O Then: T
        currentValue[0] = "A";
        alert(currentValue[0]);//Output: O Then: T
        return currentValue;
    });

为什么 currentValue[0] 没有被赋值 "A"?!?

您尝试通过索引分配给特定位置的字符串,这是不可能的,因为字符串是不可变的。 如果要更改字符串,则需要创建一个新字符串。

正如 Alex K 正确指出的那样,字符串是不可变的,您无法修改它们。

由于您使用的是.map(),这里要做的只是构造一个新字符串并返回:

var words = ["One", "Two"];
words = words.map(function (currentValue) {
    return "A" + currentValue.substring(1);
});
console.log(words); // outputs ["Ane", "Awo"];

根据经验,不应尝试使用 .map() 来修改现有值。.map()的目的是产生一组新的值,并保持原始值不变。

在 JavaScript 中,String 是基元类型,所以你不能改变它。

字符串、数字、布尔值、

空值、未定义、符号(ECMAScript 6 中的新功能)是基元类型。

最新更新