Array creation
In this chapter you will learn:
- How to use array constructor to create array
- Create an array with array literal notation
- How to create empty array
- Put different type values in one array
Array constructor
You can pass the number of item into the constructor, and the length property is set to that value.
var names = new Array(20);
document.writeln(names.length);//20
The Array constructor can accept array items:
var names = new Array("A", "B", "C");
document.writeln(names.length);//3
It's possible to omit the new operator when using the Array constructor.
<!DOCTYPE html><!--from j av a 2 s . com-->
<html>
<head>
<script type="text/javascript">
var names = Array("A", "B", "C");
document.writeln(names.length);//3
</script>
</head>
<body>
</body>
</html>
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><!--from ja v a 2s .c o m-->
<html>
<head>
<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>
Empty array
The following code creates an empty array:
<!DOCTYPE html><!-- j av a 2 s. c om-->
<html>
<head>
<script type="text/javascript">
var names = []; //creates an empty array
document.writeln(names.length);//0
</script>
</head>
<body>
</body>
</html>
Different type values in one array
The following code populates data with different type into an array.
<!DOCTYPE HTML><!--from j a v a 2 s . c o m-->
<html>
<body>
<script type="text/javascript">
var myArray = new Array();
myArray[0] = 100;
myArray[1] = "Adam";
myArray[2] = true;
</script>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
Home » Javascript Tutorial » Array