【问题标题】:Stop value going into negative in javascript停止值在 javascript 中变为负数
【发布时间】:2020-01-06 21:21:29
【问题描述】:

我有一个功能,你可以点击喜欢,你也可以点击不喜欢。我怎样才能让它不可能变成负数,这样如果你在 0 之后点击不喜欢它会保持 0?

function stem(id) {
    var antal_stemmer = document.getElementById(id).className; 
    var nyt_antal_stemmer =+ antal_stemmer + +1; 
    document.getElementById(id).className = nyt_antal_stemmer;
    var indhold = document.getElementsByClassName(id); 
    var indholdA = indhold[0].innerHTML; 
    indhold[0].innerHTML = nyt_antal_stemmer + " stemmer"; 
}
function fjern(id) {
    var antal_stemmer = document.getElementById(id).className;
    var nyt_antal_stemmer =+ antal_stemmer - +1;
    document.getElementById(id).className = nyt_antal_stemmer;
    var indhold = document.getElementsByClassName(id);
    var indholdA = indhold[0].innerHTML;
    indhold[0].innerHTML = nyt_antal_stemmer + " stemmer";
}

【问题讨论】:

  • 你减值的部分是什么?
  • @NinaScholz 可能是 var nyt_antal_stemmer =+ antal_stemmer - +1; 但是...看起来很奇怪。
  • 你为什么写- +1而不是- 1
  • 你为什么写=+?起初我把它误认为是+=,并认为你在增加nyt_antal_stemmer
  • nyt_antal_stemmer =+ antal_stemmer - +1; 是写nyt_antal_stemmer = antal_stemmer - 1; 的一种非常非常令人困惑的方式

标签: javascript count negative-number


【解决方案1】:

您可以获得最大值或零。结果是一个大于或等于零的数字。

var nyt_antal_stemmer = Math.max(0, antal_stemmer - 1); // - converts the operands to number

【讨论】:

  • 不要添加nyt_antal_stemmer。原代码中不是+=
  • 代码很误导人,实际值应该是Math.max(0, antal_stemmer - 1);
猜你喜欢
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 2021-11-23
  • 2017-10-22
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多