Add to Array
In this chapter you will learn:
Add element to the end of an array
The following code adds item to the end of an array.
<!DOCTYPE html><!-- j a va 2s.c o m-->
<html>
<head>
<script type="text/javascript">
//creates an array with three strings
var colors = ["A", "B", "C"];
colors.length = 4;
document.writeln(colors[3]); //Undefined
</script>
</head>
<body>
</body>
</html>
The following code adds items to the end of an array with the length property:
<script type="text/javascript">/*from j av a 2 s. co m*/
//creates an array with three strings
var colors = ["A", "B", "C"];
//add a color (position 3)
colors[colors.length] = "D";
//add another color (position 4)
colors[colors.length] = "E";
document.writeln(colors[0]);
document.writeln(colors[1]);
document.writeln(colors[2]);
document.writeln(colors[3]);
document.writeln(colors[4]);
document.writeln(colors[5]);
</script>
The last item in an array is always at position length - 1
.
Next chapter...
What you will learn in the next chapter:
Home » Javascript Tutorial » Array