I can't seem to figure out how to do the object part, I need to make it calculate the age dynamically. I've written most of the stuff here and it works fine the only down side is my dynamic age calculation, I don't know what I'm doing wrong and can't find my mistake.
<html>
<head>
<title>WEB PROGRAMIRANJE</title>
</head>
<body>
<script type="text/javascript">
var niza=new Array (9,8,7,6,5,4,3,2,1);
var izbrisani=niza.shift();
var izbrisanip=niza.pop();
var sortirani=niza.sort();
// form an arrey delete first and last:
// sort the arrey:
document.write(sortirani);
function babati(a,b,c)
{
var total;
total=(a b c)/3;
alert(total);
}
document.write("<br>");
</script>
<input type="button" value="Call" onClick="babati(0,5,10)";>
<script type="text/javascript">
document.write("<br>");
var ucenik=new Object();
// giving them value to object elements:
ucenik.ime="Name";
ucenik.prezime="Surname";
ucenik.godina=2021;
ucenik.roden=2003;
// printing the object elements:
document.write(ucenik.ime);
document.write("<br>");
document.write(ucenik.prezime);
document.write("<br>");
document.write(ucenik.roden);
document.write("<br>");
// The function:
// This will calculate the age dinamicly This year - Birth year:
ucenik.vozrast=function()
{
this.godina - this.roden;
}
ucenik.vozrast();
document.write(ucenik.vozrast);
//This line above prints the dynamic age:
</script>
</body>
</html>
CodePudding user response:
2 things.
Firstly, the function isn't returning any value so running it won't result in any output.
Secondly, in the document.write(ucenik.vozrast)
it writes the function definition rather than running the function and writing the output.
Below is the fixed code.
ucenik.vozrast=function()
{
return this.godina - this.roden;
}
document.write(ucenik.vozrast());
CodePudding user response:
first step you need to return your function expression. Something like this:
ucenik.vozrast= function() {
return this.godina - this.roden;
}
and when you want to paint that result in the DOM you can do something like this
let actualYears = ucenik.vozrast()
document.write(actualYears);