简体   繁体   中英

javascript string handling with array why it's print 'r' on console but not 'z'

var cun = function(cun){
    cun[0] = 'z';
    console.log(cun[0]);
    return cun;
}
cun("ratul");

Why it is print r on console but not z ? why i can't change the string using array notation?

Strings are immutable. You cannot change them. You have to create a new string for that.

function cun(str) {
    var newString = 'z' + str.substring(1);
    console.log( newString[0] );
    return newString;
}

cun('ratul');

Because strings are immutable (meaning you can't change their value) in JavaScript.

You can accomplish what you are trying to do a variety of ways, including:

var cun = function(cun){
    return "z" + cun.slice(1);
}
cun("ratul");

from the rhino book :

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

You can try:

String.prototype.replaceAt=function(index, character) {
   return this.substr(0, index) + character + this.substr(index+character.length);
}
var hello="ratul";
alert(hello.replaceAt(0, "z"));

Here is working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM