PDA

View Full Version : Put duplicate code in a function and call that?


Martin46766474
05-09-2003, 11:46 PM
I've searched for an hour and can't find the answer to this (no doubt simple) question so can someone put me on the right track?

In my script there is a section of code that is used twice, similar to this example:

var x = 3

var y = x + 4
var z= y * 2
var zz= y * 5

alert ("First - "+z+" - "+zz);

var x = 6

var y = x + 4
var z= y * 2
var zz= y * 5

alert ("Second - "+z+" - "+zz);



What I want to do is create a function:

function calculate () {
var y = x + 4
var z= y * 2
var zz= y * 5
}


So altogether I'd have something like this:


function calculate () {
var y = x + 4
var z= y * 2
var zz= y * 5
}



var x = 3

calculate();

alert ("First - "+z+" - "+zz);

var x = 6

calculate();

alert ("Second - "+z+" - "+zz);


How do I return z and zz so that they can be used?

Algorithm
05-10-2003, 12:58 AM
Return a 2-element array.function calculate () {
var y = x + 4;
return [(y * 2), (y * 5)];
}

var x = 3;
var z = calculate();

alert ("First - "+z[0]+" - "+z[1]);

x = 6;
z = calculate();

alert ("Second - "+z[0]+" - "+z[1]);

Martin46766474
05-10-2003, 03:19 AM
Excellent, thanks...