算术转换克数到千克

时间:2018-04-01 20:20:36

标签: javascript function math

当我的价值超过1000克到1公斤但我没有工作时,我正试图将克数换成千克。如果您运行代码并将值增加到2,则第一个值将是1400 g而不是我要显示的1.4 kg。



function multiplyBy() {
  var x = document.getElementById("serves").value;

  var a = 700;
  var b = 2;
  var c = 0.4;
  var d = 20;
  var e = 1;

  var kg = 1000;

  var i1 = x * a;
  var i2 = x * b;
  var i3 = x * c;
  var i4 = x * d;
  var i5 = x * e;

  if (i1 >= kg + " g") {
    document.getElementById("ing1").innerHTML = +(i1 / kg) + " g";
  } else {
    document.getElementById("ing1").innerHTML = +i1 + " g";
  }
  
  document.getElementById("ing2").innerHTML = +i2 + " g";
  document.getElementById("ing3").innerHTML = (+i3.toFixed(1)) + " g";
  document.getElementById("ing4").innerHTML = +i4 + " g";
  document.getElementById("ing5").innerHTML = +i5 + " g";
}

<input type="number" value="1" min="1" max="100" id="serves" />
<input type="button" onClick="multiplyBy()" Value="Calculate" />
<br><br>
<div id="ing1">700 g</div>
<div id="ing2">200 g</div>
<div id="ing3">0.4 g</div>
<div id="ing4">20 ml</div>
<div id="ing5">1 </div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

if (i1 >= kg + " g")

如果您将" g"追加到kg,则表示您正在比较i1 >= "1000 g"x === 21400 >= "1000 g"。由于其中一个操作数是一个字符串,它将被强制转换为NaN,而每个比较,无论i1是什么,都将返回false。你想要:

if (i1 >= kg)

然后,将+ " kg"附加到结果字符串而不是+ " g"

虽然以上解决并解释了这个问题,但我会添加一个不同的,更简单的方法,以及一些建议:

<div id="ing">
  <div>700 g</div>
  <div>200 g</div>
  <div>0.4 g</div>
  <div>20 ml</div>
  <div>1 </div>
</div>
// Get initial amounts and units from <div>s here.
const amounts = Array.from(document.getElementById("ing").children, (child) => {
      let [amount, unit] = child.innerText.split(" ");

      return {
        amount: Number(amount),
        unit: unit || "", // If there is no space in the string (e.g. just "10"), then `unit` should be the empty string (without `|| ""` it will be `undefined`).
        div: child
      };
    }),
    button = document.getElementById("button"), // Add an ID "button" to the “Calculate” button, instead of an `onclick` attribute
    kg = 1000;

function multiplyBy(){
  const serves = Number(document.getElementById("serves").value); // You use this as a number, but .value returns a string. Better convert it immediately, to avoid future errors.

  amounts.forEach(({amount, unit, div}) => {
    const multipliedAmount = amount * serves,
      useKg = unit === "g" && multipliedAmount >= kg; // This condition holds iff the multiplied amount is at least 1000 g.

    div.innerText = `${Number((multipliedAmount / (useKg ? kg : 1)).toFixed(1))} ${useKg ? "kg" : unit}`;
  });
}

button.addEventListener("click", multiplyBy); // Assign the click handler here.

// Alternatively: ditch the button and use a change listener on the `serves` input instead:
// document.getElementById("serves").addEventListener("change", multiplyBy);

这也将照顾不同的单位保留他们自己的单位,而不是成为g。有关工作示例,请参阅以下代码段:

&#13;
&#13;
// Get initial amounts and units from <div>s here.
const amounts = Array.from(document.getElementById("ing").children, (child) => {
      let [amount, unit] = child.innerText.split(" ");
      
      return {
        amount: Number(amount),
        unit: unit || "", // If there is no space in the string (e.g. just "10"), then `unit` should be the empty string (without `|| ""` it will be `undefined`).
        div: child
      };
    }),
    button = document.getElementById("button"), // Add an ID "button" to the “Calculate” button, instead of an `onclick` attribute
    kg = 1000;

function multiplyBy(){
  const serves = Number(document.getElementById("serves").value); // You use this as a number, but .value returns a string. Better convert it immediately, to avoid future errors.
  
  amounts.forEach(({amount, unit, div}) => {
    const multipliedAmount = amount * serves,
      useKg = unit === "g" && multipliedAmount >= kg; // This condition holds iff the multiplied amount is at least 1000 g.
    
    div.innerText = `${Number((multipliedAmount / (useKg ? kg : 1)).toFixed(1))} ${useKg ? "kg" : unit}`;
  });
}

button.addEventListener("click", multiplyBy); // Assign the click handler here.

// Alternatively: ditch the button and use a change listener on the `serves` input instead:
// document.getElementById("serves").addEventListener("change", multiplyBy);
&#13;
<input type="number" value="1" min="1" max="100" id="serves"/>
<input type="button" id="button" Value="Calculate"/>
<br/><br/>
<div id="ing">
  <div>700 g</div>
  <div>200 g</div>
  <div>0.4 g</div>
  <div>20 ml</div>
  <div>1 </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

if block评估为false的条件,请尝试这个。

document.getElementById("ing1").innerHTML = i1 > kg ? (i1 / kg) + 'kg' : i1 + 'g';

答案 2 :(得分:-1)

  if (i1 >= kg) {
    document.getElementById("ing1").innerHTML = (i1 / kg) + " kg";
  } else {
    document.getElementById("ing1").innerHTML = i1 + " g";
  }