Reputation: 73
Im trying some stuff for an exam and I can't make it work. It's really simple and i can't understand why is not working.
<!DOCTYPE html>
<html>
<head>
<title>Exercici 2</title>
<script type="text/javascript">
//rep 2 paràmetres d'entrada i els suma
function suma(a, b) {
alert(arguments.length);
//donaria undefined, ja que no existeix el argument amb índex 2, tindria que ser [1]
alert(arguments[2]);
//3 + 5 = 8
return a + b;
}
var result = suma(3,5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
I know alert(arguments[2]);
will show undefined.
Upvotes: 0
Views: 733
Reputation: 535
Necesitas un onload para que funcione pues llamas el getElement By Id, antes de que exista el elemento y no tiene sentido. Ademas tu salida debe ser un string.
You need a "onload" function for this case, because you declare your getElemetnById before the element, also your output in your function should be a string.
<script type="text/javascript">
//rep 2 paràmetres d'entrada i els suma
function suma(a, b) {
//a = argumento 0, b = argumento 1
return (a + b).toString();
}
//estas ejecutando esto, sin antes existir el id="result", por tanto debes esperar
// aque primero se cree, y luego ejecutar, eso se hace añadiendo esto:
window.onload = function(){ //espera a que todos los elements html se creen.
var result = suma(3,5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
}
</script>
Upvotes: 2
Reputation: 3113
When working with Sums, it is advisable to add parseInt
,
this way you can also add var result = suma('3', 5);
and it will return 8, if you dont have the parseInt and you parse a string '3'
it will concat it and will return 35
function suma(a, b) {
//3 + 5 = 8
return parseInt(a) + parseInt(b);
}
var result = suma(3, 5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
Upvotes: 0
Reputation: 24915
Issue is you are calling function before DOM is rendered. So result
is not available. Move your script after body.
<html>
<head>
<title>Exercici 2</title>
</head>
<body>
<div id="result">
</div>
</body>
<script type="text/javascript">
//rep 2 paràmetres d'entrada i els suma
function suma(a, b) {
//3 + 5 = 8
return a + b;
}
var result = suma(3, 5);
document.getElementById("result").innerHTML += "<strong>Suma</strong>: 3 + 5 = " + result + "<br>";
</script>
</html>
Upvotes: 3