JavaScript Arrays - split() method Tutorial

This exercise uses the .split method on a predetermined array and returns the midterm grade and final grade of a student in an alert box. A function processes the number inputted by the user to return the values in a string. A <form> button is used to call the function.

Code Example
  1. var student = new Array(5)
  2. student [0] = "Jane Doe,22,80,90 "
  3. student [1] = "John Doe,21,70,65 "
  4. student [2] = "Jack Smith,30,80,80 "
  5. student [3] = "Jen Smith,30,90,70 "
  6. student [4] = "Fred Brown,25,90,90 "
  7. function grade() {
  8. var SN = parseInt(prompt("Please type your student number between 0 and 4 to determine which student results you require")); // prompts for a number and returns this to SN
  9. if (SN >=0 && SN<=4) { // if else statement to verify a number has been used
  10. var student_array = student[SN].split(","); //splits the given array
  11. var mid = parseInt((student_array[2]));var full = parseInt((student_array[3]));
  12. var allgrade = (mid*.4)+(full*.6);
  13. alert("Hello " + student_array[0] + " Your midterm grade for this year is " + student_array[2] + " and your final grade is " + student_array[3] + " your total grade being " +allgrade+"%"); // uses each [1] number of the array to determine which part of the array string should be displayed
  14. } else {
  15. alert("Please write a valid number");
  16. grade()
  17. }
  18. }

This second exercise will use the prompt() method to prompt a user to type a couple of words separated by spaces. The .split method splits the string into a new array, delimited by commas. The delimited array is then displayed in an alert box.

Code Example
  1. function splits() {
  2. var b = prompt("Type in a couple of words separated by spaces");
  3. var temp = new Array();
  4. temp = b.split(' ');
  5. alert(temp);
  6. }