JavaScript program to Create and Access the
Elements of an Array.
The JavaScript
Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.
<html>
<title>Basic Javascript Array Example</title>
<script language="javascript">
// Empty array
var empty = [];
// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];
alert(fruits[1]);
</script>
</head>
<body>
</body>
</html>
To add elements to an array in javascript, just define a new element at the end of the array.
You can also use push() to 'push' a new element onto the end of the array, or unshift() to add elements to the start of an array:
Create
an Array
varfruits=['Apple','Banana'];
console.log(fruits.length);
// 2
Access
(index into) an Array item
varfirst=fruits[0];
// Apple
varlast=fruits[fruits.length-1];
// Banana
Loop
over an Array
fruits.forEach(function(item,index,array){
console.log(item,index);
});
// Apple 0
// Banana 1
Add
to the end of an Array
varnewLength=fruits.push('Orange');
// ["Apple", "Banana", "Orange"]
Remove
from the end of an Array
varlast=fruits.pop();// remove Orange (from the end)
// ["Apple", "Banana"];
Remove
from the front of an Array
varfirst=fruits.shift();// remove Apple from the front
// ["Banana"];
Add
to the front of an Array
varnewLength=fruits.unshift('Strawberry')// add to the front
// ["Strawberry", "Banana"];
Find
the index of an item in the Array
fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]
varpos=fruits.indexOf('Banana');
// 1
Remove
an item by index position
varremovedItem=fruits.splice(pos,1);// this is how to remove an item
// ["Strawberry", "Mango"]
Remove
items from an index position
varvegetables=['Cabbage','Turnip','Radish','Carrot'];
console.log(vegetables);
// ["Cabbage", "Turnip", "Radish", "Carrot"]
varpos=1,n=2;
varremovedItems=vegetables.splice(pos,n);
// this is how to remove items, n defines the number of items to be removed,
// from that position(pos) onward to the end of array.
console.log(vegetables);
// ["Cabbage", "Carrot"] (the original array is changed)
console.log(removedItems);
// ["Turnip", "Radish"]
Copy
an Array
varshallowCopy=fruits.slice();// this is how to make a copy
// ["Strawberry", "Mango"]
Link to sectionSyntax
[element0, element1, ..., elementN]
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
No comments:
Post a Comment