Javascript Data Type How to - Swap array element








Question

We would like to know how to swap array element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  w ww.  j av a 2s.  c o m-->
var testArray = ['first', 'second', 'third'];
var swap = function(theArray, indexA, indexB) {
    var temp = theArray[indexA];
    theArray[indexA] = theArray[indexB];
    theArray[indexB] = temp;
};
swap(testArray, 0, 1);
document.writeln(testArray);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: