[英]Is there a method for accessing variables in the parent scopes of a function
[英]Accessing scopes from a function
我无法将此 customerName 变量转换为大写。 我知道我错过了一些小东西。
var customerName = 'bob'
function upperCaseCustomerName() {
customerName.toUpperCase();
return customerName;
}
很容易犯错误, 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
我在同一个训练营,也遇到了麻烦。 我最初编写的代码如下:
var customerName = 'bob'
function upperCaseCustomerName(){
return customerName.toUpperCase();
}
好吧,测试没有通过! 我在这上面呆了好几个小时。 我的问题是误解了测试想要什么——>“upperCaseCustomerName():编写一个访问该全局 customerName 变量的函数,并将其大写。” 如果您在 vs 代码上打开 indexTests.js 文件,您将获得更多说明。
虽然我上面的第一个代码将返回值 BOB,但这根本不是测试所要求的。 该测试要求您将 customerName 的值修改或重新分配为“BOB”,以便它为我们提供 BOB 的值。
function upperCaseCustomerName(){
return customerName = customerName.toUpperCase();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.