简体   繁体   中英

Javascript assigning a method to an array value

I'm trying to figure out why I cannot assign the toUpperCase method to a specific value in an array (see below). I am a little confused because I thought objects were mutable and manipulated by reference? Maybe I am looking at it backwards?

var ary = ["hello", "there", "world"];
ary[0][0] = ary[0][0].toUpperCase();
console.log(ary[0][0]); // returns lowercase h

Any clarification would help me out a lot.

Since Strings are immutable in JavaScript, assigning a new character to an index of a String will not change the string at all. You need to create a new String like this

ary[0] = ary[0][0].toUpperCase() + ary[0].substr(1);
# H

We are creating a new string with the first letter capitalized and the rest of the string as it is.

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