【问题标题】:Accessing scopes from a function从函数访问范围
【发布时间】:2021-10-16 23:23:08
【问题描述】:

我无法将此 customerName 变量转换为大写。我知道我错过了一些小东西。

var customerName = 'bob'

 function upperCaseCustomerName() {
    customerName.toUpperCase();
    return customerName;
}

【问题讨论】:

    标签: javascript scope global


    【解决方案1】:

    很容易犯错误,toUpperCase() 函数没有就地执行,这意味着返回结果,更正如下:

    var customerName = 'bob'
    
     function upperCaseCustomerName() {
        return customerName.toUpperCase();
    }
    

    【讨论】:

      【解决方案2】:

      你需要返回转换后的值

      var customerName = 'bob'
      
      function upperCaseCustomerName() {
          return customerName.toUpperCase();
      }
      
      upperCaseCustomerName() // 'BOB'
      
      

      【讨论】:

        【解决方案3】:

        “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>

        【讨论】:

        • 你明白了。我需要将它分配给另一个变量!
        【解决方案4】:

        我建议在这里使用参数并且独立于你的函数的外部范围:

        let customerName = "bob";
        
        function upperCaseCustomerName(name) {
          return name.toUpperCase();
        }
        
        upperCaseCustomerName(customerName); // BOB
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-27
          • 2021-04-23
          • 2021-12-30
          • 1970-01-01
          • 2012-01-13
          • 1970-01-01
          • 2016-04-04
          • 2020-05-31
          相关资源
          最近更新 更多