Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

switching values with 3rd variable 1

Status
Not open for further replies.

onressy

Programmer
Mar 7, 2006
421
CA
Hi i'm trying something and am wonder what the most effecient way to switch the value of two variables without creating a third variable, and also so that its dynamic, meaning what ever the values or a or b are it will work:

var a = 3;
var b = 5;

// so the result will be b=3 and a=5, again without the use of a third variable

Any suggestions?

Thanks
 
Provided that you're using numbers, you can use this method (note that it won't work with strings or most other data types)

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

var a = 5;
var b = 3;
alert("Values before swap\n\na: " + a + "\nb: " + b);
[gray][i]//here's the swapping magic[/i][/gray]
[!]a = a + b;
b = a - b;
a = a - b;[/!]
alert("Values after swap\n\na: " + a + "\nb: " + b);

</script>
<style type="text/css"></style>
</head>
<body>
</body>
</html>

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top