var cars = ["Saab", "Volvo", "BMW"]; // Spaces and line breaks are not important. A declaration can span multiple lines: var cars = [ "Saab", "Volvo", "BMW" ];
Adding elements with high indexes can create undefined "holes" in an array:
Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes.
var person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; var x = person.length; // person.length will return 3 var y = person[0]; // person[0] will return "John"
The best way to loop through an array, is using a "for" loop:
var fruits, text, fLen, i; fruits = ["Banana", "Orange", "Apple", "Mango"]; fLen = fruits.length; text = "<ul>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; }
var cars = new Array("Saab", "Volvo", "BMW");
With JavaScript, the full array can be accessed by referring to the array name:
var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars;
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
var person = ["John", "Doe", 46];
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars;
The real strength of JavaScript arrays are the built-in array properties and methods:
var x = cars.length; // The length property returns the number of elements var y = cars.sort(); // The sort() method sorts arrays
The length property of an array returns the length of an array (the number of array elements).
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // the length of fruits is 4
The easiest way to add a new element to an array is using the push method:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
var fruits, text, fLen, i; fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[6] = "Lemon"; fLen = fruits.length; text = ""; for (i = 0; i < fLen; i++) { text += fruits[i] + "<br>"; } document.getElementById("demo").innerHTML = text; Output: Banana Orange Apple Mango undefined undefined Lemon
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
var person = []; person["firstName"] = "John"; person["lastName"] = "Doe"; person["age"] = 46; var x = person.length; // person.length will return 0 var y = person[0]; // person[0] will return undefined
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.
There is no need to use the JavaScript's built-in array constructor new Array()
.
Use []
instead.
These two different statements both create a new empty array named points:
var points = new Array(); // Bad var points = []; // Good var points = new Array(40, 100, 1, 5, 25, 10); // Bad var points = [40, 100, 1, 5, 25, 10]; // Good
The new
keyword only complicates the code. It can also produce some unexpected results:
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
What if I remove one of the elements?
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
var fruits = ["Banana", "Orange", "Apple", "Mango"]; typeof fruits; // returns object
The typeof operator returns object because a JavaScript array is an object.
To solve this problem ECMAScript 5 defines a new method Array.isArray()
:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = Array.isArray(fruits); output: true
<p id="demo"></demo> <script> var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ] document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; </script> output: Volvo 2016 Saab 2001 BMW 2010
var mixedArray = [ 20, // numeric "Tarana", // string true, // boolean function arrayFunction(){ console.log("this is a function inside an array") }, // function {type:"volvo", year:1990}, // object [20, "tarana", {type:"audi", year:1995}] ] console.log(mixedArray[0]); console.log(mixedArray[1]); console.log(mixedArray[2]); console.log(mixedArray[3].arrayFunction()); console.log(mixedArray[4]); console.log(mixedArray[5]); console.log(mixedArray[5][2].type);
array.forEach(function(currentValue,index,arr), thisValue)
The forEach()
method calls a provided function once for each element in an array, in order.
Note: forEach()
does not execute the function for array elements without values.
var words = ["one", "two", "three", "four"]; words.forEach(function(word) { console.log(word); // if (word === "two") { words.shift(); } }); output is: one two three four
<button onclick="numbers.forEach(myFunction)">Try it</button> <p>Sum of numbers in array: <span id="demo"></span></p> <script> var sum = 0; var numbers = [65, 44, 12, 4]; function myFunction(item) { sum += item; demo.innerHTML=sum; } </script>
<button onclick="numbers.forEach(myFunction)">Try it</button> <p id="demo"></p> <script> demoP = document.getElementById("demo"); var numbers = [4, 9, 16, 25]; function myFunction(item, index) { demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br />"; } </script> output is: index[0]: 4 index[1]: 9 index[2]: 16 index[3]: 25
What if we had a couple of shopping carts of items? Say you wanted to total the cost of your shopping cart. The following example totals the cost of all items from our shopping carts using the forEach()
method.
var total_cost = 0; function add_to_total_cost(amount) { total_cost += amount.cost; } var shopping_cart_1 = [ { item: 'shirt', cost: 22 }, { item: 'shorts', cost: 26 } ]; var shopping_cart_2 = [ { item: 'cereal', cost: 4 }, { item: 'milk', cost: 3 }, { item: 'eggs', cost: 2 } ] shopping_cart_1.forEach(add_to_total_cost); shopping_cart_2.forEach(add_to_total_cost); console.log(total_cost); //57
One scenario where I choose a for loop over the forEach() method is when I want to break out of a loop early. Imagine I had a longer list of products and as soon as I found one that matches some criteria, I want to perform some action. If I used forEach(), it would iterate over every single product resulting in unnecessary iterations, potentially causing performance issues depending on how long the array is. With a for loop, you have the ability to break out early and stop the loop from continuing. For example:
for (var i = 0; i < products.length; i++) { if (matchesSomeCriteria(products[i])) { doSomething(); break; } }
Article by morioh.com
Content for the first footer section.
Content for the second footer section.
Content for the third footer section.