Array Length
The number of items in an array is stored in the length property.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B", "C"]; //creates an array with three strings
var names = []; //creates an empty array
document.writeln(colors.length); //3
document.writeln(names.length); //0
</script>
</head>
<body>
</body>
</html>
length is not read-only.
By setting the length property, you can remove or add items to the end of the array.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B", "C"]; //creates an array with three strings
colors.length = 2;
document.writeln(colors[2]); //Undefined
colors[99] = "D"; //add a color (position 99)
document.writeln(colors.length); //100
</script>
</head>
<body>
</body>
</html>
The following code adds item to the end of an array.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B", "C"]; //creates an array with three strings
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:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B", "C"]; //creates an array with three strings
colors[colors.length] = "D"; //add a color (position 3)
colors[colors.length] = "E"; //add another color (position 4)
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>
</head>
<body>
</body>
</html>
The last item in an array is always at position length - 1.
Home
JavaScript Book
Essential Types
JavaScript Book
Essential Types
Array:
- The Array Type
- Array Built-in Methods
- Detecting Arrays
- Get and set array values
- Enumerating the Contents of an Array
- Array Length
- Array join() method
- Array concat()
- Array indexOf()
- Array lastIndexOf()
- Array every()
- Array filter() filters array with the given function.
- Array map()
- Array forEach()
- push() and pop():Array Stack Methods
- push(), shift():Array Queue Methods
- Array reduce()
- Array reduceRight()
- reverse():Reordering array
- Array slice()
- Array some()
- Array splice()
- Array sort()
- toString(), toLocaleString() and valueOf Array
- Array unshift()