javascript - 将字符串修改为数组

标签 javascript arrays string

我不明白为什么我的 word[1] 返回的是 a 而不是 i,你能帮我理解一下吗?

var word = 'tangle';
document.write(word[1]); //returns 'a'
word[1] = 'i';
document.write(word[1]); //returns 'a'

(其实我是想做这个的,是我的方法不对吗?)

//convert the first letter of each word of the string in upper case
var string = 'the quick brown fox';
stringSpl = string.split(' ');
for (var j=0; j<stringSpl.length; j++){
  stringSpl[j][0] = stringSpl[j][0].toUpperCase(); //this line is the faulty one
}
document.write(stringSpl.join(' '));

最佳答案

字符串在 Javascript 中是不可变的。

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it.

资料来源:David Flanagan,在他的书“JavaScript, The Definitive Guide, 4th edition”(ISBN:978-0613911887)中。

关于javascript - 将字符串修改为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34121052/

相关文章:

mysql - 如何使用MySQL删除两个固定字符串之间的随机字符串?

java - 从键盘读取数据并存储在字符串数组中

javascript - 错误字符串长度比较javascript

php - 使用 jquery 和 php 处理目录中的文件 - 获取状态并更新进度条

java - 如何动态填充二维数组

c - C语言中如何打印enum中的所有内容?

javascript - 来自 Javascript 数组的 Html 表

javascript - 在 div 中包围希伯来语和英语文本

javascript - 如何模拟返回 promise 的对象?

c - 将字符串分配给变量