繁体   English   中英

在本地重新分配全局变量,而不在全局范围内更改它们。 JavaScript的

[英]Reassign global variables locally without changing them in the global scope. JavaScript

我知道如何使我的代码按预期工作,但我尝试使用相同的变量名并遇到以下问题:

是否可以在submitSettings()中重新分配最小和最大变量,以便在全局范围内保持不变? (您可以在代码中看到为什么我希望它们在全局范围内保持不变。)

如果是,请告诉我如何以及在哪里可以了解有关此主题的更多信息。

  // here i get the HTML elements from <input>.
  let min = document.getElementById('min')
  let max = document.getElementById('max')

  function submitSettings() {
    // here i want to validate the values from those HTML elements while maintaining the same variable names (min, max).
    function validateSettings() {
      min = min.valueAsNumber // My question: How can i reassign global variables locally without changing them in global scope?
      let max = max.valueAsNumber // Or: How can i get max variable from the scope from outside (from global scope)?

      min >= max ? console.log("Not good") : console.log("OK")
    }

    validateSettings()

    // here i want to clear <input>, but i can't because min and max are not HTML elements anymore, rather numbers.
    min.value = ''
    max.value = ''
  }

由于代码突出显示的原因,通常将阴影变量视为不良做法。 从一个范围到另一个范围很难维护。 解决此问题的方法有多种,但是它们主要依靠为本地上下文重命名变量。

// here i get the HTML elements from <input>.
  const min = document.getElementById('min')
  const max = document.getElementById('max')

  function submitSettings() {
    // here i want to validate the values from those HTML elements while maintaining the same variable names (min, max).
    function validateSettings() {
      let minValue = min.valueAsNumber // My question: How can i reassign global variables locally without changing them in global scope?
      let maxValue = max.valueAsNumber // Or: How can i get max variable from the scope from outside (from global scope)?

      minValue >= maxValue ? console.log("Not good") : console.log("OK")
    }

    validateSettings()


    min.value = ''
    max.value = ''
  }

严格来说, let关键字是唯一的,因为它创建了块范围的变量,因此允许以下内容

const global = 1;
const local = () => {
  let global = 2;
  console.log(global);
}

local(); // logs 2
console.log(global); // logs 1

但我认为这不是很好的做法

您还可以使用validateSettings是一个函数并为其创建minmax参数的事实。

// here i get the HTML elements from <input>.
  const min = document.getElementById('min')
  const max = document.getElementById('max')

  function submitSettings() {
    // here i want to validate the values from those HTML elements while maintaining the same variable names (min, max).
    function validateSettings(min, max) {    
      min >= max ? console.log("Not good") : console.log("OK")
    }

    validateSettings(min.value, max.value)


    min.value = ''
    max.value = ''
  }

暂无
暂无

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

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