我不明白为什么我的 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/