Java Reference
In-Depth Information
have the
trim()
method. It returns a new string with all leading and trailing whitespace removed.
For example:
var name = prompt("Please enter your name");
name = name.trim();
alert("Hello, " + name);
This code prompts users to enter their name. You then trim their input of whitespace and use the
resulting value in a greeting that is displayed in an
alert
box. So, if the user entered
" Jim"
,
he'd still only see
"Hello, Jim"
in the
alert
box because you trimmed his input.
array objects
You saw how to create and use arrays in Chapter 2, and this chapter mentioned earlier that they are
actually objects.
In addition to storing data,
Array
objects provide a number of useful properties and methods you
can use to manipulate the data in the array and find out information such as the size of the array.
Again, this is not an exhaustive look at every property and method of
Array
objects, but rather just
some of the more useful ones.
Finding Out how Many elements Are in an Array—the length property
The
length
property gives you the number of elements within an array. Sometimes you know
exactly how long the array is, but in some situations you may have been adding new elements to an
array with no easy way of keeping track of how many have been added.
You can use the
length
property to find the index of the last element in the array. This is illustrated
in the following example:
var names = [];
names[0] = "Paul";
names[1] = "Jeremy";
names[11] = "Nick";
document.write("The last name is " + names[names.length - 1]);
Note
Note that you have inserted data in the elements with index positions
0
,
1
, and
11
. The array index starts at
0
, so the last element is at index
length ‐ 1
,
which is
11
, rather than the value of the
length
property, which is
12
.
Another situation in which the
length
property proves useful is where a JavaScript method returns
an array it has built itself. For example, in the next chapter, you see that the
String
object has the
split()
method, which splits text into pieces and passes back the result as an
Array
object. Because