How to use $.each method for an array in jQuery?

364 views Asked by At
function calcTotalScore(){
    var arr = ["A","B","C","D","E","F"];
    $.each(arr, function(n,val){
        calcTotal(val);
    });
}

calcTotal(value){
// sample code
}

I am using the above function calcTotalScore() in Velocity Template Language(VTL), but it says:

Encountered "," Was expecting one of:
   <EOF> 
    "(" ...
   <RPAREN> ...
   <ESCAPE_DIRECTIVE> ...
   <SET_DIRECTIVE> ...
   "##" ...
   "\\\\" ...
   "\\" ...
   <TEXT> ...
   "*#" ...
   "*#" ...
   <STRING_LITERAL> ...
   <IF_DIRECTIVE> ...
   <STOP_DIRECTIVE> ...
   <INTEGER_LITERAL> ...
   <FLOATING_POINT_LITERAL> ...
   <WORD> ...
   <BRACKETED_WORD> ...
   <IDENTIFIER> ...
   <DOT> ...
   "{" ...
   "}" ...

What am I doing wrong?

2

There are 2 answers

0
a'r On BEST ANSWER

VTL is interpreting jQuery's $ as the start of a variable. It then complains because a variable name cannot start with a dot.

You have two options:

  1. Escape the dollar with a backslash, eg. \$
  2. Use jQuery instead of $
3
gabel On

UPDATE

see answer of a'r :D


You're just missing a "function" in front of calcTotal ;)

http://fiddle.jshell.net/gabel/7SvUY/1/

function calcTotalScore(){
    var arr = Array("A","B","C","D","E","F");
    $.each(arr, function(n,val){
        calcTotal(val);
    });
}

function calcTotal(value){
// sample code
    alert(value);
}

calcTotalScore();