在下面的代码中,变量“key
”没有大写,即使任何其他变量(如steve [j])如果在调用中替换“key
”时也会大写。函数capitaliseFirstLetter()
。
有人可以告诉我为什么吗?
for(key in aray) {
steve = aray[key];
for(j = 0; j < steve.length; j++){
diff = steve[j].slice(key.length);
if(diff == ""){
diff = "_";
}
diffs.push(diff);
var firstLetterUpper = /^[A-Z]/.test(steve[j]);
if(firstLetterUpper){
capitaliseFirstLetter(key)
alert(key])
}
}
}
function capitaliseFirstLetter(string){
return string.charAt(0).toUpperCase() + string.slice(1);
}
答案 0 :(得分:6)
key = capitaliseFirstLetter(key)
alert(key)
字符串对象按值传递给函数。所以它不会改变你应该重新分配价值
答案 1 :(得分:2)
如果您的目标是捕获每个单词,可以更简单地完成:
for (key in aray) {
var steve = aray[key];
console.log(toTitleCase(steve));
// if you want to change the aray value
aray[key] = toTitleCase(steve);
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}