Passing arrays to a function

A

aliensite

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;
else if(i%2) // odd
args += ' (' + arguments;
else
args += ', ' + arguments + ')';
}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>
 
L

Lasse Reichstein Nielsen

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++ ) {

You call foo with *one* argument. That argument is an array
containing values, but it is only one array.
if(i==0)
args += arguments;


Here you add the array to a string, so it is converted to a string.

Solutions:
function foo(arr) { // and change "arguments" to "arr"
or
alert(foo.apply(this,myArray1));

/L
 
D

Douglas Crockford

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>
function foo() {
var args = "start ";
for( var i=0 ; i < arguments.length; i++ ) {
if(i==0)
args += arguments;
else if(i%2) // odd
args += ' (' + arguments;
else
args += ', ' + arguments + ')';
}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>


You only use arguments when you have a variable number of arguments. In this
case, you have a single argument, which will be an array.

So replace the first line with

function foo(a) {

and replace all occurrences of 'arguments' with 'a'.

http://www.crockford.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,077
Messages
2,570,569
Members
47,205
Latest member
KelleM857

Latest Threads

Top