最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript count number of steps - Stack Overflow

programmeradmin5浏览0评论

How can I count number of steps between different numbers.

I have a method that takes a number and runs a code snippet with the number. I need to see if the number is the number right next to the other or two steps, three steps, four steps over or below etc.

Ex. I send a number of 1 to the method. The next number sent is 4. I then need to find out how many steps over one it is etc in this case 3 steps over 1 should be the result.

Any clues?

How can I count number of steps between different numbers.

I have a method that takes a number and runs a code snippet with the number. I need to see if the number is the number right next to the other or two steps, three steps, four steps over or below etc.

Ex. I send a number of 1 to the method. The next number sent is 4. I then need to find out how many steps over one it is etc in this case 3 steps over 1 should be the result.

Any clues?

Share Improve this question edited Jun 20, 2011 at 14:50 MacMac 35.4k55 gold badges153 silver badges224 bronze badges asked Jun 20, 2011 at 13:10 TobiasTobias 4943 gold badges14 silver badges31 bronze badges 1
  • 4 I think 4 - 1 is what you're after. – pimvdb Commented Jun 20, 2011 at 13:13
Add a ment  | 

4 Answers 4

Reset to default 7

You can use a function with a closure:

var value = (function() {
  var previousValue = null;
  return function(id) {
      if (previousValue !== null) {
          if(previousValue >= id) {
              alert("Difference: -" + (previousValue - id));
          }
          else alert("Difference: +" + (id - previousValue));
      }
    previousValue = id;
  };
})();

See an example fiddle here.

A simple subtraction!

var stepx = 1
var stepy = 4
var diff = stepy - stepx 
alert (diff)

added fix for negative steps

   var previousNumber = 0;

    function countSteps(number) {
        var result = (number - previousNumber);
        previousNumber = number;
        return (result<0) ? result*-1 : result;
    }

Sorry got interrupted

<html>
<head>
<script>
var cnt="";
function countAndSave(num) {
  var text = (cnt==="")?num:num+":"+Math.abs(num-cnt)+"/"+cnt
  cnt=num;
  return text
}
window.onload=function() {
  document.getElementById("output").innerHTML +="<br />"+countAndSave(1);
  document.getElementById("output").innerHTML +="<br />"+countAndSave(3);
  document.getElementById("output").innerHTML +="<br />"+countAndSave(4);
  document.getElementById("output").innerHTML +="<br />"+countAndSave(1);
  document.getElementById("output").innerHTML +="<br />"+countAndSave(2);
  document.getElementById("output").innerHTML +="<br />"+countAndSave(3);
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论