为什么是Infinity?简单的JavaScript练习[已关闭]

pb3skfrl  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(141)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

3小时前关闭
Improve this question
我试图做一个简单的JS练习,但我不能让我的代码工作。它不适用于我的一个变量。谁能告诉我解释一下。

salary = [1000, 2000, 3000]
salary2 = [4000, 3000, 1000, 2000]

var average = function(salary) {
  let acaSalary = salary

  let minSalary = Infinity;
  let maxSalary = 0;
  let sumatoria = 0;
  let dividendo = acaSalary.length - 2

  for (let i = 0; i < acaSalary.length; i++) {
    if (acaSalary[i] > maxSalary) {
      maxSalary = acaSalary[i]
    } else if (acaSalary[i] < minSalary) {
      minSalary = acaSalary[i]
    }
  }

  for (let i = 0; i < acaSalary.length; i++) {
    sumatoria = sumatoria + acaSalary[i];
  }

  let prom = (sumatoria - maxSalary - minSalary) / dividendo
  console.log(sumatoria)
  console.log(maxSalary)
  console.log(minSalary)
  console.log(dividendo)

  return prom
};

console.log(average(salary))
console.log(average(salary2))

我无法解释这是怎么回事。

hmmo2u0o

hmmo2u0o1#

问题是在条件之间使用了else if。这意味着它只能更新maxSalaryminSalary,但不能同时更新两者。但是在循环的第一次迭代中,salary小于Infinity,大于0,所以你需要更新这两个变量。
只有当条件互斥时,才应该使用else if。如果每个条件都为真并且需要处理,则对它们使用if

salary = [1000, 2000, 3000]
salary2 = [4000, 3000, 1000, 2000]

var average = function(salary) {
  let acaSalary = salary

  let minSalary = Infinity;
  let maxSalary = 0;
  let sumatoria = 0;
  let dividendo = acaSalary.length - 2

  for (let i = 0; i < acaSalary.length; i++) {
    if (acaSalary[i] > maxSalary) {
      maxSalary = acaSalary[i]
    } 
    if (acaSalary[i] < minSalary) {
      minSalary = acaSalary[i]
    }
  }

  for (let i = 0; i < acaSalary.length; i++) {
    sumatoria = sumatoria + acaSalary[i];
  }

  let prom = (sumatoria - maxSalary - minSalary) / dividendo
  console.log(sumatoria)
  console.log(maxSalary)
  console.log(minSalary)
  console.log(dividendo)

  return prom
};

console.log(average(salary))
console.log(average(salary2))

相关问题