The Array Type
JavaScript arrays are ordered lists of data. JavaScript arrays can hold any type of data in each slot. JavaScript arrays are dynamically sized.
Arrays can be created in two ways. The first is to use the Array constructor:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var names = new Array();
document.writeln(names.length);//0
</script>
</head>
<body>
</body>
</html>
You can pass the number of item into the constructor, and the length property is set to that value.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var names = new Array(20);
document.writeln(names.length);//20
</script>
</head>
<body>
</body>
</html>
The Array constructor can accept array items:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var names = new Array("A", "B", "C");
document.writeln(names.length);//3
</script>
</head>
<body>
</body>
</html>
It's possible to omit the new operator when using the Array constructor.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var names = Array("A", "B", "C");
document.writeln(names.length);//3
</script>
</head>
<body>
</body>
</html>
Create an array with array literal notation
The second way to create an array is by using array literal notation.
The following code creates an array with three strings:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["red", "blue", "green"]; //creates an array with three strings
document.writeln(colors.length);//3
</script>
</head>
<body>
</body>
</html>
The following code creates an empty array:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var names = []; //creates an empty array
document.writeln(names.length);//0
</script>
</head>
<body>
</body>
</html>
The following code populates data with different type into an array.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var myArray = new Array();
myArray[0] = 100;
myArray[1] = "Adam";
myArray[2] = true;
</script>
</body>
</html>
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()