【发布时间】:2021-10-16 23:23:08
【问题描述】:
我无法将此 customerName 变量转换为大写。我知道我错过了一些小东西。
var customerName = 'bob'
function upperCaseCustomerName() {
customerName.toUpperCase();
return customerName;
}
【问题讨论】:
标签: javascript scope global
我无法将此 customerName 变量转换为大写。我知道我错过了一些小东西。
var customerName = 'bob'
function upperCaseCustomerName() {
customerName.toUpperCase();
return customerName;
}
【问题讨论】:
标签: javascript scope global
很容易犯错误,toUpperCase() 函数没有就地执行,这意味着返回结果,更正如下:
var customerName = 'bob'
function upperCaseCustomerName() {
return customerName.toUpperCase();
}
【讨论】:
你需要返回转换后的值
var customerName = 'bob'
function upperCaseCustomerName() {
return customerName.toUpperCase();
}
upperCaseCustomerName() // 'BOB'
【讨论】:
“toUpperCase() 方法不会改变原始字符串”-w3Schools. 相反,您必须将其存储在 var 中,如下所示。
<body>
<span id="name"></span>
<script>
var customerName = 'bob'
function upperCaseCustomerName() {
var name=customerName.toUpperCase();//Here
return name;
}
document.getElementById("name").innerText=upperCaseCustomerName();
</script>
</body>
【讨论】:
我建议在这里使用参数并且独立于你的函数的外部范围:
let customerName = "bob";
function upperCaseCustomerName(name) {
return name.toUpperCase();
}
upperCaseCustomerName(customerName); // BOB
【讨论】: