为什么我的函数无法正确传递计算?

时间:2020-06-27 05:08:02

标签: javascript

我正在使用JS中的转换计算器,无法弄清楚为什么我的打印功能会产生“未定义”而不是根据计算得出的数字输出。

该程序的目的是要求用户输入重量和他们想要访问的行星,根据所选行星的相对重力进行计算,然后在该行星上打印新的重量。

这是我的代码的一部分:

// Ask for current weight input
let currentWeight = prompt('What is your current weight?');

// Ask for planet user wants to visit
let newPlanet = prompt('where do you want to visit?');

// function with input weight * relative gravity on selected planet 
// round answer to 2d
if (newPlanet === 'Earth' || newPlanet === 'earth') {
  return newWeight = (currentWeight * 1).toFixed(2);
}

// Calculated output
function calculation(currentWeight, newPlanet) {
  console.log('Your weight on ' + newPlanet + ' is ' + newWeight);
}

calculation(); // "Your weight on undefined is undefined"
// This is not the output I want.

3 个答案:

答案 0 :(得分:0)

一些建议:

1-您不在函数外部使用return语句

2-避免为函数的参数命名与全局变量相同的名称

3-阅读此article可以更好地了解范围。

祝你好运

检查此代码:

// ask for current weight input
let currentWeight = prompt('What is your current weight?');

// ask for planet user wants to visit
let newPlanet = prompt('where do you want to visit?');

// function with input weight * relative gravity on selected planet 
// round answer to 2d

function newWeight () {
  if (newPlanet === 'Earth' || newPlanet === 'earth') {
    return (currentWeight * 1).toFixed(2);
  }
}

// calculated output
function calculation() {
    console.log('Your weight on '+ newPlanet + ' is ' + newWeight ());
}

calculation();

答案 1 :(得分:0)

您的函数calculation无法访问您的变量newWeight

您需要从函数中提取变量。

// ask for current weight input
let currentWeight = prompt('What is your current weight?');

// ask for planet user wants to visit
let newPlanet = prompt('where do you want to visit?');

let newWeight = 0
// function with input weight * relative gravity on selected planet 
// round answer to 2d
if (newPlanet === 'Earth' || newPlanet === 'earth') {
    newWeight = (currentWeight * 1).toFixed(2);
}

// calculated output
function calculation(currentWeight, newPlanet) {
    console.log('Your weight on ' + newPlanet + ' is ' + newWeight);
}
calculation();

答案 2 :(得分:0)

有2个问题

  • 函数外部有一个return语句
  • newWeight并未在任何地方定义,因此将其视为全局变量,因此该值将打印为undefined

// calculated output
function calculation() {
  let currentWeight = prompt('What is your current weight?');

  // ask for planet user wants to visit
  let newPlanet = prompt('where do you want to visit?');
  let newWeight = currentWeight
  // function with input weight * relative gravity on selected planet 
  // round answer to 2d
  if (newPlanet === 'Earth' || newPlanet === 'earth') {
    newWeight = (currentWeight * 1).toFixed(2);
  }
  console.log('Your weight on ' + newPlanet + ' is ' + newWeight);
}
calculation();