[英]Why array appears as a string, but when I print it to console it print it as an array? ReactJS functional component
[英]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");
為什么在控制台上是print r而不是z? 為什么我不能使用數組表示法更改字符串?
字符串是不可變的。 您無法更改它們。 您必須為此創建一個新字符串。
function cun(str) {
var newString = 'z' + str.substring(1);
console.log( newString[0] );
return newString;
}
cun('ratul');
因為字符串在JavaScript中是不可變的(意味着您無法更改其值)。
您可以通過多種方式完成您嘗試做的事情,包括:
var cun = function(cun){
return "z" + cun.slice(1);
}
cun("ratul");
從犀牛書中 :
在JavaScript中,字符串是不可變的對象,這意味着它們中的字符可能不會更改,並且對字符串的任何操作實際上都會創建新的字符串。 字符串是通過引用而不是值來分配的。 通常,當通過引用分配對象時,通過一個引用對該對象所做的更改將通過對該對象的所有其他引用可見。 但是,由於無法更改字符串,因此您可以對一個字符串對象有多個引用,而不必擔心字符串值會在您不知道的情況下發生變化
你可以試試:
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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.