开发者

JavaScript String as Array: Read but no Write

For JavaScript in most browsers*, you can read a character from a String by treating it like an Array. However, in all the browsers I've tried (IE9, Chrome, Firefox), you can't write to it like an Array.

For example:

var string = 'hello world';
alert(string[0]);//alerts 'h'
alert(string);//alerts 'hello world'

string[0]='j';
alert(string[0]);//alerts 'h'
alert(string);//alerts 'hello world'

This has repercussions for more than just JavaScript developers:

jelloPeople.roam();

Does anybody know the reasoning behind this?

For example, I've looked at Mozilla's documentation, and they allude to it but don't give an explanation:

    "..trying to set a character via indexing does not throw an error, but the string itself is unchanged."

Bottom Line: It is strange and confusing to me that some array properties were given to Strings and not others.

UPDATE:

Ok, so JavaScript Strings are immutable objects, but why? It seems like operations such as the above would be faster if they weren't immutable (change 1 character as opposed to making a new 11 character string). In fact, I don't see a case 开发者_运维百科with String functions where performance would be impacted negatively if they weren't immutable, but I see several where performance would be improved. Also, there is no true multi-threading in JavaScript, so no advantage to immutables there.

(removed and will research this and possibly ask in a new quesion)


*Not IE 6 or 7


This simply because javascript strings are immutable by design; once created they cannot be changed.


I think it might be because strings in JavaScript are immutable. Notice that every string function doesn't actually change the string itself, but returns a new one. This is the same for changing characters directly, it wouldn't work with an immutable model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜