Click to See Complete Forum and Search --> : Help! Functions


highspeed4eva
04-22-2005, 02:33 PM
Hello,

I have to write a javascript program that uses a function which takes an array as input and calculates the square roots of its elements. I am as beginner as a beginner can get and this is my homework. I am stumped. This is what I have come pup with:


<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- Created on: 4/22/2005 -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Function Using array as input</title>
<script language="javascript">
function squares(numArray){math.sqrt=0;len=numArray.length;for(i=0;i<len;i++){math.sqrt+=math.sqrt(numArray);}
numArray = new Array (36,49,81); math.sqrt;for (i=0;i<3;i++){math.sqrt +=math.sqrt(numArray[i]);}
document.write("The square roots of these" + numArray.length + "numbers<br />");for (i=0;i<3;i++){ document.write (numArray[i]+",");}document.write("is<h2>"+math.sqrt+"</h2>");}</script>
</head>
<body>
</body>
</html>


What am I doing wrong? Any help will be greatly appreciated.

HaganeNoKokoro
04-22-2005, 02:46 PM
A few things:

You seem to have a variable called "math.sqrt". This won't work; variable names should be a letter or underscore followed by letters, numbers, and underscores.

You also seem to be using "math.sqrt" to refer to the javascript built-in square root function "Math.sqrt". Javascript is case-sensitive (capital/lowercase is important) so the two are not the same.

The variable you are trying to store the square roots in is being treated as a number right now, and you're adding to it every time. Are you trying to print a list of the square roots, or the sum of the square roots. If it's supposed to be a list, you'd be better off with an array.

A note on style: You seem to be avoiding new lines. This makes your code all but impossible to read.

Warren86
04-22-2005, 03:05 PM
<HTML>
<Head>
<Script Language=JavaScript>

var numArray = new Array("36","49","81");

function squares(){

isResult = document.getElementById('resultText');
tmp = "";
for (i=0; i<numArray.length; i++)
{tmp += Math.sqrt(numArray[i])+","}
tmp = tmp.substring(0,tmp.length-1);
isResult.innerHTML = "The square roots of these numbers:<br> " +numArray+ " <br>are:<br>"+"<h2>"+tmp+"</h2>";
}

window.onload=squares;


</Script>
</Head>
<Body>
<Div id='resultText'></Div>

</Body>
</HTML>

highspeed4eva
04-22-2005, 03:47 PM
Thank you!

Warren86
04-22-2005, 03:57 PM
You're welcome. Take care.