Array Type
In this chapter you will learn:
The Array Type
JavaScript arrays are ordered lists of data. It can hold any type of data in each slot. JavaScript arrays are dynamically sized.
Arrays can be created by using the array constructor:
<!DOCTYPE html><!-- j a v a 2 s. c o m-->
<html>
<head>
<script type="text/javascript">
var names = new Array();
document.writeln(names.length);//0
</script>
</head>
<body>
</body>
</html>
Array methods
The JavaScript Array object defines a number of methods you can use to work with arrays.
Method | Description | Returns |
---|---|---|
concat(otherArray) | Concatenates the array with the specified array. Multiple arrays can be specified. | Array |
join(separator) | Joins all of the elements in the array to form a string. The argument specifies the character used to delimit the items. | string |
pop() | Treats an array like a stack, and removes and returns the last item in the array. | object |
push(item) | Treats an array like a stack, and appends the specified item to the array. | void |
reverse() | Reverses the order of the items in the array in place. | Array |
shift() | Like pop, but operates on the first element in the array. | object |
slice(start,end) | Returns a sub-array. | Array |
sort() | Sorts the items in the array in place. | Array |
unshift(item) | Like push, but inserts the new element at the start of the array. | void |
Get and set array values
To get and set array values, you use square brackets and provide the zero-based numeric index:
<!DOCTYPE html><!-- ja v a2 s. co m-->
<html>
<head>
<script type="text/javascript">
var colors = ["A", "B", "C"]; //define an array of strings
document.writeln(colors[0]); //A,display the first item
colors[2] = "black"; //change the third item
document.writeln(colors[2]); //,display the third item
colors[3] = "brown"; //add a fourth item
document.writeln(colors[3]); //display the fourth item
</script>
</head>
<body>
</body>
</html>
The following code changes the first element in the array:
var myArray = [ 100, "Adam", true ];
myArray[0] = "Tuesday";
document.writeln("Index 0: " + myArray[0]);
Next chapter...
What you will learn in the next chapter:
- 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
Home » Javascript Tutorial » Array