JavaScript Examples
Dave Braunschweig
Arrays
// This program demonstrates array processing, including: // display, total, max, min, parallel arrays, sort, // fixed arrays, dynamic arrays, and multidimensional arrays. main() function main() { var names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily']; var ages = [49, 48, 26, 19, 16]; displayArray(names); displayArray(ages); var total = calculateSum(ages); var maximum = calciulateMaximum(ages); var minimum = calculateMinimum(ages); output('total: ' + total); output('maximum: ' + maximum); output('minimum: ' + minimum); demonstrateParallelArrays(names, ages); ages.sort(); displayArray(ages); demonstrateFixedArray(); demonstrateDynamicArray(); demonstrateMultidimensionalArray(); } function displayArray(array) { for (var index = 0; index < array.length; index++) { output('array[' + index + '] = ' + array[index]); } } function calculateSum(array) { var total = 0; for (var index = 0; index < array.length; index++) { total += array[index]; } return total; } function calculateMaximum(array) { var maximum = array[0]; for (var index = 1; index < array.length; index++) { if (maximum < array[index]) { maximum = array[index]; } } return maximum; } function calculateMinimum(array) { var minimum = array[0]; for (var index = 1; index < array.length; index++) { if (minimum > array[index]) { minimum = array[index]; } } return minimum; } function demonstrateParallelArrays(names, ages) { for (var index = 0; index < names.length; index++) { output(names[index] + ' is ' + ages[index] + ' years old'); } } function demonstrateFixedArray() { var array = new Array(5); for (var index = 0; index < array.length; index++) { var number = Math.floor(Math.random() * 100); array[index] = number; } displayArray(array); } function demonstrateDynamicArray() { var array = []; for (var index = 0; index < 5; index++) { var number = Math.floor(Math.random() * 100); array.push(number); } displayArray(array); } function demonstrateMultidimensionalArray() { var game = [ ['X', 'O', 'X'], ['O', 'O', 'O'], ['X', 'O', 'X'] ]; for (var row = 0; row < 3; row++) { var line = ''; for (var column = 0; column < 3; column++) { line += game[row][column]; if (column < 2) { line += ' | '; } } output(line); } } function output(text) { if (typeof document === 'object') { document.write(text); } else if (typeof console === 'object') { console.log(text); } else { print(text); } }
Output
array[0] = Lisa array[1] = Michael array[2] = Ashley array[3] = Jacob array[4] = Emily array[0] = 49 array[1] = 48 array[2] = 26 array[3] = 19 array[4] = 16 total: 158 maximum: 49 minimum: 16 Lisa is 49 years old Michael is 48 years old Ashley is 26 years old Jacob is 19 years old Emily is 16 years old array[0] = 16 array[1] = 19 array[2] = 26 array[3] = 48 array[4] = 49 array[0] = 55 array[1] = 4 array[2] = 46 array[3] = 88 array[4] = 49 array[0] = 28 array[1] = 95 array[2] = 13 array[3] = 60 array[4] = 60 X | O | X O | O | O X | O | X