Passing arrays to a function

Giganews Newsgroups
Subject: Passing arrays to a function
Posted by:  aliensiā€¦@excite.com (aliensite)
Date: 31 Jul 2003

I am trying to pass arrays of various lengths to a function.
However the values are read as a string.
What is the easiest way to pass the values?

<script type="text/javascript">
<!--
function foo() {
  var args = "start ";
  for( var i=0 ; i < arguments.length; i++ ) {
      if(i==0)
        args += arguments[i];
      else if(i%2) // odd
        args += ' (' + arguments[i];
      else
        args += ', ' + arguments[i] + ')';
  }args += ' end';
    return args;
}

myArray1 = new Array('x', 2, 3)
myArray2 = new Array('y', 5, 7, 11, 13)

alert(foo(myArray1));  // start 1,2,3 end
alert(foo(myArray2));  // start 2,3,5,12,13 end

// alerts should be:      start 1 (2, 3) end
//                        start 2 (3, 5) (12, 13) end
// -->
</script>

Replies