简体   繁体   English

Javascript为数组值分配方法

[英]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). 我试图弄清楚为什么我不能将toUpperCase方法分配给数组中的特定值(请参见下文)。 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. 由于字符串在JavaScript中是不可变的,因此为字符串的索引分配新字符根本不会更改字符串。 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. 我们正在创建一个新字符串,第一个字母大写,其余字符串保持原样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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