|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Using String ArraysSo far, you've used arrays of numbers. JavaScript also allows you to use string arrays, or arrays of strings. This is a powerful feature that enables you to work with a large number of strings at the same time. Creating a String ArrayYou declare a string array in the same way as a numeric arrayin fact, JavaScript does not make a distinction between them: names = new Array(30); You can then assign string values to the array elements: names[0] = "Henry J. Tillman"; names[1] = "Sherlock Holmes"; As with numeric arrays, you can also specify a string array's contents when you create it. Either of the following statements would create the same string array as the preceding example: names = new Array("Henry J. Tillman", "Sherlock Holmes");
names = ["Henry J. Tillman", "Sherlock Holmes"];You can use string array elements anywhere you would use a string. You can even use the string methods introduced earlier. For example, the following statement prints the first five characters of the first element of the names array, resulting in Henry: document.write(names[0].substring(0,5)); Splitting a StringJavaScript includes a string method called split, which splits a string into its component parts. To use this method, specify the string to split and a character to divide the parts: test = "John Q. Public";
parts = test.split(" ");In this example, the test string contains the name John Q. Public. The split method in the second statement splits the name string at each space, resulting in three strings. These are stored in a string array called parts. After the example statements execute, the elements of parts contain the following:
JavaScript also includes an array method, join, which performs the opposite function. This statement reassembles the parts array into a string: fullname = parts.join(" ");The value in the parentheses specifies a character to separate the parts of the array. In this case, a space is used, resulting in the final string John Q. Public. If you do not specify a character, commas are used. Sorting a String ArrayJavaScript also includes a sort method for arrays, which returns an alphabetically sorted version of the array. For example, the following statements initialize an array of four names and sort it: names[0] = "Public, John Q."; names[1] = "Tillman, Henry J."; names[2] = "Bush, George W."; names[3] = "Mouse, Mickey"; sortednames = names.sort(); The last statement sorts the names array and stores the result in a new array, sortednames. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |