By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,784 Members | 1,182 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,784 IT Pros & Developers. It's quick & easy.

Passing arrays to a function

P: n/a
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>
Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
al*******@excite.com (aliensite) writes:
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[i];


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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2

P: n/a
> 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[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>


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

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.