views:

72

answers:

3

I have this function:

function countLitreKgSums(cProductIds){
  var cLitreKgSums = new Array();
  var cWeek = 0;
  for(i=0;i<cProductIds.length;i++){
    var cLitreKgSum = 0;
    $("#plan_table td[class='week']").each(function(){
            cWeek = $(this).html();
            var cLitreKgValue = $("input[name*='plan_table_week" + cWeek + "_prod" + cProductIds[i] + "_']").val();
            if (cLitreKgValue == "") {
                cLitreKgValue = 0;
            }
            cLitreKgValue = cLitreKgValue.replace(/,/g, '.').replace(/[^\d\.]/g, '').replace(/\s/g, '');
            cLitreKgValue = parseFloat(cLitreKgValue);
            cLitreKgSum += cLitreKgValue;
       });
       cLitreKgSum = Math.round(cLitreKgSum * 100) / 100;
       cLitreKgSums[i] = cLitreKgSum;
  }
  return cLitreKgSums;
  //console.log(cLitreKgSums);
}

I get error message that .replace is not a function but in other functions it works as it should. What is the difference?

+8  A: 

cLitreKgValue might be a number at the point where you try to call replace on it, not a string. In which case, the error is correct - numbers don't have a replace method.

Andrzej Doyle
...and to *correct* it ('cause I'm thinking that anleon is looking for an answer to that as well), change `cLitreKgValue = 0;` to `cLitreKgValue = "0";`
T.J. Crowder
Thanks alot! That seemed to do the trick.
anleon
+1  A: 

Change this:

cLitreKgValue.replace(/,/g, '.')

to

("" + cLitreKgValue).replace(/,/g, '.')
Jonathon
Better to change `cLitreKgValue = 0;` to `cLitreKgValue = "0";` I think...
Nick Craver
@Nick Craver why better?
Jonathon
@Jonathon - You're not appending a string for every element that *doesn't* need any work that way. Though it's better yet to make an overall change, I added an answer showing this.
Nick Craver
+3  A: 

While the other answers work (and are correct, numbers don't have .replace(), it's a String method), I think an overall structure change is better, like this:

$("#plan_table td[class='week']").each(function(){
    cWeek = $(this).html();
    var cLitreKgValue = $("input[name*='plan_table_week" + cWeek + "_prod" + cProductIds[i] + "_']").val();
    if (cLitreKgValue !== "") {
      cLitreKgValue = cLitreKgValue.replace(/,/g, '.').replace(/[^\d\.]/g, '').replace(/\s/g, '');
      cLitreKgSum += parseFloat(cLitreKgValue);
    }
});

There's no reason to do all that work when you know it's 0 and doesn't affect the result, so if "" means 0 and anything += 0 has no net effect, just skip it :)

Nick Craver
Thanks for that too =)
anleon