0

I am splitting a function that is in format '0:00:00' using the colon. Once I have done this, I am doing some calculations with the separate numbers by saving them to a separate variable. The values where I am trying to access them after the .split function are giving 'undefined' and I am unsure why.

I have tried using replace instead of split, but split is the easier way using less code to do what I want(ability to have the values separated).

This is what my console shows when entering the time vie input box: enter image description here I think the error is being caused because of the time being updated with each key stroke so to speak instead after the whole time is entered.

calcPace(time, distance){
  var minutes = 0;
  var seconds = 0



  var hms = time+'';   // your input string
  var intDist = distance+'';
  intDist = parseFloat(distance, 10);
  var a = hms.split(':'); // split it at the colons

  // minutes are worth 60 seconds. Hours are worth 60 minutes.
  var totalMinutes = ((+a[0]) * 60) + ((+a[1])) + (+a[2] / 60);

  console.log(a[0]); //gives 'undefined, should be a number 0-6

  var paceValue = totalMinutes / intDist;
  minutes = Math.floor(paceValue);
  seconds = Math.round((paceValue - minutes) * 60);

  console.log(totalMinutes)
  if(seconds < 10) {
        seconds = "0" + seconds;
    }

  var paceValue = minutes+":"+seconds;

  this.setState({
     pace: paceValue//paceValue
  });
}

the function is being called here

handleButtonPress(){
  console.log("pressed");
  this.calcPace(this.time, this.distance);

}

When I print paceValue, the result is NaN:NaN, as well as minutes and seconds. When checking in the array locations after the split, the values are undefined. I need there to be numbers there and the expected output would be something like '5:24' or similar.

3
  • How exactly is the function being called? Commented May 6, 2019 at 14:52
  • @Pointy see recent most edit Commented May 6, 2019 at 14:54
  • 1
    OK well what is this.time() in that handleButtonPress() function? Commented May 6, 2019 at 14:54

1 Answer 1

1

This error can happen because of these lines

var a = hms.split(':')
...
var totalMinutes = ((+a[0]) * 60) + ((+a[1])) + (+a[2] / 60);
...
minutes = Math.floor(paceValue);
seconds = Math.round((paceValue - minutes) * 60);

If hms.split(':') doesn't return an array with length of 3. a[x] can be undefined.

If you divide undefined by a number, it will return NaN.

So the reason you are getting undefined is that probably hms isn't a string with 3 :
e.g. ('0:00:00').

I recommend you doing some checking and conditionally creating totalMinutes depending of a.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.