简体   繁体   English

StandardJS 未将 array.push() 识别为重新分配

[英]StandardJS not recognising array.push() as reassignment

I've declared an empty array before a loop that then gets populated as the loop runs.我在循环之前声明了一个空数组,然后在循环运行时填充该数组。 My code works fine but when I lint using StandardJS it tells me that the array is never reassigned and should be declared as a const.我的代码工作正常,但是当我使用 StandardJS 进行 lint 时,它告诉我数组永远不会重新分配,应该声明为 const。 If i did this then I wouldn't be able to add values to my array and my code wouldn't work.如果我这样做了,那么我将无法向我的数组添加值,并且我的代码将无法工作。 This also means i cant use standard --fix because it breaks my code.这也意味着我不能使用标准 --fix因为它破坏了我的代码。

let primeFactors = []
while (number > 1) {
  if (isPrime(divisor)) {
    if (number % divisor === 0) {
      primeFactors.push(divisor)
      number = number / divisor
    } else {
      divisor++
    }
  } else {
    divisor++
  }
}

Am i missing something here?我在这里错过了什么吗?

You can, and should use const .您可以并且应该使用const

The name const is a bit of a misnomer - it is merely saying that the variable, once declared, cannot be redeclared or reassigned - that is, it always points at the same object in memory (or more generally, is always the same value as when it was first created) For further explanation, see this post on MDN . const这个名字有点用词不当——它只是说变量一旦声明,就不能重新声明或重新分配——也就是说,它总是指向 memory 中相同的 object(或更一般地说,总是与首次创建时)有关进一步说明,请参阅MDN 上的这篇文章

Note however that the object can be mutable, even if it's declared as const.但是请注意,object 可以是可变的,即使它被声明为 const。 Just because primeFactors is always pointing at the same array doesn't mean that array can't grow/shrink/change.仅仅因为primeFactors总是指向同一个数组并不意味着该数组不能增长/缩小/改变。

In my javascript, very few of my variables are let - I use const pretty much everywhere, which makes code much easier to read and reason about.在我的 javascript 中,我的变量很少被let - 我几乎在任何地方都使用const ,这使得代码更易于阅读和推理。 (The only times I use let is the occasional for each loops, and occasional helper algorithmic methods) (我使用let的唯一时间是每个循环的偶尔使用,以及偶尔使用的辅助算法方法)

So the linter is technically right, and encouraging best practice - For example, the linter is protecting you from code such as the following - which would cause eg an Uncaught TypeError: Cannot read property 'push' of null :因此,linter 在技术上是正确的,并鼓励最佳实践 - 例如,linter 保护您免受以下代码的影响 - 这会导致例如Uncaught TypeError: Cannot read property 'push' of null

let primeFactors = []
while (number > 1) {
  if (isPrime(divisor)) {
    if (number % divisor === 0) {
      primeFactors.push(divisor)
      number = number / divisor
    } else {
      divisor++
      primeFactors = null // There's no reason to do this, but it's theoretically possible!
    }
  } else {
    divisor++
  }
}

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

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