Jump to content

Javascript array question


Matt512

Recommended Posts

1st question.

<script language="JavaScript">
var a = [1,2,3,4,5,6,7,8,9,10];
var display = whatisthis(a, a.length);
document.writeln("<h1>Output:" + display + "</h1>");
function whatisthis(b, chkdis) {
if (chkdis == 1)
return b[0];
else
return b[chkdis - 1] + whatisthis(b, chkdis - 1);
}
</script>

2nd question.
What is the value of the variables b and d after the following
JavaScript code is executed?

<script type="text/javascript">
var a = 5, b = 2, c = 2, d = 1;
var fruit = new Array();
fruit[0] = "pear";
fruit[1] = "apple";
fruit[2] = "guava";
fruit[3] = "orange";
fruit[4] = "grape";
fruit[5] = "avocado";
fruit[6] = "cherry";
if( b <= c ){
d = a – b * c;
b = fruit[d];
} else {
d = a;
b = fruit[c];
}
alert( "b now contains: " + b + " and d contains: " + d);
</script>

Can anyone explain to me what are the answers of those two questions and how you came to it?

Link to comment
Share on other sites

This looks copied and pasted from some kind of homework question. Can you tell me how far you've gotten on your own and which line of code you don't understand?

 

The language attribute on the script tag is deprecated and shouldn't be used.

Link to comment
Share on other sites

I believe the first question is to figure out what the function does, that's why the function is named "whatisthis".

 

The function in the first question will probably not work as the creator intended due to the ambiguity of the + operator.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...