Introduction to Arrays
Introduction to Arrays
Fundamentnals of Arrays
Introduction
As seen in C#, an array is a list of items. Each item, also called an element, occupies a specific position. In C#, all the elements of an array must be of the same type. In JavaScript, every element of an array is primarily an object, which means it can be anything.
Introduction to Creating an Array
In JavaScript, the primary formula to create an array is:
var variable-name = [eleament_1, eleament_2], ..., eleament_n];
Start as done when declaring a variable and assign the square brackets, [], to it. If you want to create an array doesn't (yet) have elements, leave the square brackets empty. Here is an example:
var members = [];
If you want to create an array that has a single element, include that element in the square brackets. If an element is a number, just type it. Here is an example:
var price = [250];
If an element is Boolean, specify its value as true or false. Here is an example:
var diagnosis = [ true ];
If an element is a character (letter or symbol) or a string, include it in single or double-quotes. Here are examples:
var name = ["William"]; var thaiFood = ['Panang']; var aphorism = ["absence of evidence is not evidence of absence"];
An array typically contains more than one element. In this case, create the list of items and separate them with commas. Here are examples:
var prices = [30, 9, 850, 28, 3705, 8]; var thaiFood = ['Yum Neau', 'Curry Puffs', 'Tom Kha Soup', 'Shrimp Bikini' ];
In JavaScript, an array can contain different types of elements. Here is an example:
var diagnosis = [ true, false, "positive", 'negative' ];
An Undefined Element
When creating an array, if you don't want to specify an element, you can leave its placeholder empty. Here is an example:
var title = [ "Absence", , "Malice" ];
The element in the empty space is said to be undefined.
Introduction to Accessing an Array
Accessing an Array as an Object
There are various ways you can access an array in JavaScript. To access an array as an object, simply use its name. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Exercise</title> </head> <body> <p class="foodForThoughts">Food for Thoughts</p> <script> var aphorism = ["Absence of evidence is not evidence of absence"]; document.querySelector('.foodForThoughts').innerHTML = aphorism; </script> </body> </html>
When you access an array by its name, the result is the list of elements separated by commas. The above code would produce:
Accessing an Element
As it's the case for all C-based languages, the elements of an array are organized in an indexed list. The first element is at index 0, the second element occupies Position 1, and so on. As seen in C#, to access an element of an array, enter its index in the square brackets following its name. Here are examples:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Diagnosis</title> </head> <body> <h1>Diagnosis</h1> <table border="3"> <tr> <td><span class="first"></span></td> <td><span class="second"></span></td> </tr> <tr> <td><span class="third"></span></td> <td><span class="fourth"></span></td> </tr> </table> <script> var diagnosis = [ true, false, "positive", 'negative' ]; document.querySelector('.first').innerHTML = diagnosis[0] + " " + diagnosis[2]; document.querySelector('.second').innerHTML = diagnosis[0] + " " + diagnosis[3]; document.querySelector('.third').innerHTML = diagnosis[1] + " " + diagnosis[2]; document.querySelector('.fourth').innerHTML = diagnosis[1] + " " + diagnosis[3]; </script> </body> </html>
This would produce:
Counting and Looping in JavaScript
Introduction
Like every C-based language, JavaScript supports the same counting and looing mechanisms we reviewed for C#.
while something is Going on
To let you scan an array, JavaScript provides the same while keyword as C#. As a reminder, the formula to use it is:
@while(condition) { statement1; statement2; statement_n; };
The while loop can be illustrated as follows:
As seen in C#, you must ifrst provide a starting point. Then, in the body of the loop, create one or more statements to execute. In the parentheses of the loop, create a condition that will be checked to decide whether to continue or not. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Thai Food</title> </head> <body> <h1>Thai Food</h1> <script> var i = 0; var thaiFood = ['Yum Neau', "Roti Kanai w/Yellow Curry Chicken", 'Curry Puffs', "Tom Kha Soup", 'Shrimp Bikini' ]; document.write("<ul>"); while (i < 5) { document.write("<li>" + thaiFood[i] + "</li>"); i++; } document.write("</ul>"); </script> </body> </html>
This would produce:
doing Something while Going On
To do something in a loop before checking a condition, JavaScript supports the same do...while combination as C#. As a reminder, the formula to follow is:
do { statement1; statement2; statement_n } while (condition);
The do...while condition can be illustrated as follows:
The description is the same we saw for C#.
Going for a Loop
The classic way to perform a loop is with the for keyword. It is the same we reviewed for C#. It uses the following formula:
for(start; end; frequency) { statement1; statement2; . . . statement_n; }
This loop works the same way we reviewed for C#.
For the Elements in a List or Array
If you have a list or array and want to visit each member, the JavaScript language provides another for loop that adds the in keyword. The formula to follow is:
for(variable in list-or-array) { statement1; statement2; . . . statement_n }
As seen with the classic for loop, start with a variable in the parentheses and initialize that variable. It is followed by the in keyword and the name of a list or array. The variable represents the index as is the case for the for loop. This means that, in the body of the for...in loop, to access the index of an element, get the variable of the variable. To access an item, type the name of the list or array, apply and square brackets, and pass the index in the square brackets. Otherwise, in the body of the loop, create the necessary statements.
Primary Characteristics and Operations on Arrays
The Size of an Array
The size of an array is the number of elements it contains. It is also referred to as the length of the array.
Increasing an Array
In C and C-based languages, an array is a fixed number of elements in a list and by definition, you can neither add new items to it nor delete an item. JavaScript doesn't follow those rules. In JavaScript, at any time, you can add a new element to an array. To do this, type the name of the array and apply the square brackets to it. In the square brackets, enter an index equal to or higher than the length of the array. Then assign a new value. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Study Levels</title>
</head>
<body>
<h1>Study Levels</h1>
<script>
var levels = [ "Freshman", "Sophomore" ];
document.write("<ul>");
for (var counter in levels) {
document.write("<li>" + levels[counter] + "</li>");
}
document.write("</ul>");
levels[2] = "Junior";
document.write("<h2>Additional</h2>");
document.write("<ul>");
for (var counter in levels) {
document.write("<li>" + levels[counter] + "</li>");
}
document.write("</ul>");
</script>
</body>
</html>
Updating an Element
Updating an element consists of changing its value. This feature is available in all arrays of the C-based language. To update an element, type the name of the array and apply the square brackets to it. In the brackets, enter a positive index lower than the size of the array. Then assign the desired value. Here are examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Thai Food</title>
</head>
<body>
<h1>Thai Food</h1>
<script>
var i = 0;
var thaiFood = ['Yum Neau', "Roti Kanai w/Yellow Curry Chicken",
'Panang', "Kee Mao Fried Rice",
'Curry Puffs', "Tom Kha Soup", 'Shrimp Bikini'];
document.write("<ul>");
while (i < 7) {
document.write("<li>" + thaiFood[i] + "</li>");
i++;
}
document.write("</ul>");
var food = thaiFood[1];
thaiFood[2] = "Pad Cashew Nut";
thaiFood[1] = thaiFood[6];
thaiFood[6] = food;
document.write("<h2>Replacement</h2>");
i = 0;
document.write("<ul>");
while (i < 7) {
document.write("<li>" + thaiFood[i] + "</li>");
i++;
}
document.write("</ul>");
</script>
</body>
</html>
This would produce:
The Array Class
Introduction
To support arrays, the JavaScript language provides a class named Array. It is equipped with properties to provide various pieces of information about an array and methods to perform operations.
To create an array, you can declare a variable of and initialize it with Array. The class is equipped with a constructor that can take 0 or more arguments. You can create and pass an array as argument. You can create the array directly in the parentheses of the constructor. Here is an example:
var Senegal = new Array(["Jola", "Toucouleur", "Maure", "Wolof", "Serer", "Fula","Soninke", "Mandinka", "Bassari"]);
To access the array as an object, use the name of the variable. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Senegal</title> </head> <body> <h1>Senegal</h1> <p class="Senegal"></p> <script> var Senegal = new Array(["Jola", "Toucouleur", "Maure", "Wolof", "Fula","Soninke", "Mandinka", "Bassari"]); document.querySelector(".Senegal").innerHTML = Senegal; </script> </body> </html>
This would produce:
You can first declare the variable and initialize it with an empty parentheses Array object. To add an element to the array, use the name of the variable and apply the square brackets to it. In the brackets, enter a positive index lower than the current number of elements. Then assign the desired value to it. You can then access each element as we know already. Here are examples:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Senegal</title> </head> <body> <h1>Senegal</h1> <script> var Senegal = new Array(); Senegal[0] = "Jola"; Senegal[1] = "Toucouleur"; Senegal[2] = "Maure"; Senegal[3] = "Wolof"; Senegal[5] = "Fula"; Senegal[6] = "Soninke"; Senegal[7] = "Mandinka"; Senegal[8] = "Bassari"; document.write("<ul>"); for (var group in Senegal) { document.write("<li>" + Senegal[group] + "</li>"); } document.write("</ul>"); </script> </body> </html>
As see with C#, when you declare a variable and initialize it as an array, the variable is automatically an object of type Array. As a result, such a variable benefits from the properties and methods of the Array class.
The Length of an Array
As mentioned previously, the size or length of an array is the number of elements it contains. To give you this piece of information, the Array class is equipped with a property named length. Here is an example of using this property:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DC Comics Characters - Cyborg</title>
</head>
<body>
<h1>DC Comics Characters</h1>
<script>
var counter = 0;
var characters = [ 'Superman', 'Green Lantern', 'Batman',
'Wonder Woman', 'The Flash', 'Aquaman' ];
document.write('<ul>');
do {
document.write('<li>' + characters[counter] + '</li>');
} while (counter < characters.length)
document.write('</ul>');
</script>
</body>
</html>
This would produce:
Adding an Element to an Array
To let you add new elements to an existing array, the Array class is equipped with a method named push. Its syntax is:
push(element1, element2, ..., element_n);
To call this method, apply it to an array variable. To add one element, pass it as argument. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Senegal</title>
</head>
<body>
<h1>Senegal</h1>
<script>
var Senegal = new Array();
Senegal[0] = "Jola";
Senegal[1] = "Toucouleur";
Senegal[2] = "Maure";
Senegal[3] = "Wolof";
Senegal[4] = "Fula";
Senegal[5] = "Soninke";
Senegal[6] = "Mandinka";
Senegal[7] = "Bassari";
Senegal.push("Serer");
document.write("<ul>");
for (var group in Senegal) {
document.write("<li>" + Senegal[group] + "</li>");
}
document.write("</ul>");
</script>
</body>
</html>
This would produce:
To add more than one element, create their list in the square bracket and pass the whole array as argument.
Removing an Element from an Array
To let you delete an existing element from an array, the Array class is equipped with a method named pop. Its syntax is:
pop();
To call this method, apply it to an array variable. If the array has at least one element, this method would remove the last element.
Arrays and Functions
Introduction
You can create an array in the body of a function. If you don't yet have the elements for the array, you can first initialize the variable with empty square brackets as we saw in our introduction. When you are ready, you can add elements to the array using any of the techniques we reviewed. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>DC Comics Characters - Cyborg</title> </head> <body> <h1>DC Comics Characters</h1> <script> function defineSuperHero() { var counter = 0; var superman = []; superman.push(['Heat Vision']); document.write('<h2>Superman Characteristics</h2>'); superman.push(["X-Ray Vision"]); superman.push(["Freeze Breath"]); superman.push('Super Strength'); superman.push(["Healing Factor"]); superman.push(['Super Human Hearing']); } defineSuperHero(); </script> </body> </html>
Since this is a local variable, remember that it cannot be accessed outside the function. To access an element of the array inside the function, use the name of the array, apply the square brackets to it, and pass the desired index. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Department Store</title> </head> <body> <h1>Department Store</h1> <form name="DepartmentStore" method="get"> <table> <tr> <td>Item #:</td> <td><input type="text" name="itemNumber" /></td> </tr> <tr> <td>Category:</td> <td><input type="text" name="category" /></td> </tr> <tr> <td>Item Name/Description:</td> <td><input type="text" name="itemName" /></td> </tr> <tr> <td>Unit Price:</td> <td><input type="text" name="unitPrice" /></td> </tr> </table> </form> <script> function analyze() { 'use strict'; var itemNumber = 803942; var categories = ["Men", "Women", "Boys", "Girls", "Accessories"]; var itemName = "Black Striped Dress"; var unitPrice = 188.85; document.DepartmentStore.itemNumber.value = itemNumber; document.DepartmentStore.category.value = categories[1]; document.DepartmentStore.itemName.value = itemName; document.DepartmentStore.unitPrice.value = unitPrice; }; analyze(); </script> </body> </html>
Otherwise, when declaring the variable, if you know the elements you want to use, add them. Here are examples:
function analyze() {
'use strict';
var itemNumber = 803942;
var categories = ["Men", "Women", "Boys", "Girls", "Accessories"];
var itemName = "Black Striped Dress";
var unitPrice = 188.85;
};
An Element from a Function
As we mentioned for C#, the value of an element can come from a function. Here is an example:
<script type="text/javascript">
var conclusion = "";
var speedLimit = 30;
var drivingSpeed = 75;
var prices = [30, 15, show(drivingSpeed), 758, 60 ];
function show(current) {
var difference = drivingSpeed - speedLimit;
if (current > difference) {
conclusion = "Driver's License Suspended: You were caught driving at " + difference + "/MPH over the speed limit.";
}
return difference;
}
</script>
Returning an Array from a Function
You can create a function that returns an array. To do this, define the array in the body of the function. Somewhere at the end of the function, return that array. Here is an example:
function defineSuperHero() { var superman = []; superman.push(['Heat Vision']); superman.push(["X-Ray Vision"]); superman.push(["Freeze Breath"]); superman.push('Super Strength'); superman.push(["Healing Factor"]); superman.push(['Super Human Hearing']); return superman; }
You can also create the array directly after the return keyword:
function createNumbers() {
return [40, 30, 5, 840, 9, 8 ];
}
To use the returning array, you can call the function and assign its call to a variable. After doing, you can use the variable as array. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DC Comics Characters - Cyborg</title>
</head>
<body>
<h1>DC Comics Characters</h1>
<script>
function defineSuperHero() {
var superman = [];
superman.push(['Heat Vision']);
superman.push(["X-Ray Vision"]);
superman.push(["Freeze Breath"]);
superman.push('Super Strength');
superman.push(["Healing Factor"]);
superman.push(['Super Human Hearing']);
return superman;
}
var powers;
var counter = 0;
document.write('<h2>Superman Characteristics</h2>');
powers = defineSuperHero();
document.write('<ul>');
do {
document.write('<li>' + powers[counter] + '</li>');
counter++;
} while (counter < powers.length)
document.write('</ul>');
</script>
</body>
</html>
This would produce:
An Array as Argument
You can create a function that uses a parameter that is an array. When creating the function, simply specify the name of the parameter. Consider the following example:
<script> function prepare(jobs) { } </script>
Notice that our function has a parameter. Except for the fact that its name is plural, we don't know what that parameter represents. When calling the function, of course you must pass an argument. In this case, the argument would be an array.
When it comes to the elements or values of the array argument, you have various options depending on what you are trying to do. You can create a function that only knows that it must receive an array but the function would provide its own local values. In this case, when calling the function, you can pass empty square brackets for the argument (as if you don't (yet) have an array). Here is an example:
<script>
function prepare(title, jobs) {
}
prepare("Jobs Performed", []);
</script>
At this time, the Prepare() function is aware that it receives an array argument (the second argument). You can then create a local array assigned to the argument and use that array. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>College Park Auto-Repair</title> </head> <body> <h1>College Park Auto-Repair</h1> <script> function prepare(title, jobs) { var counter = 0; jobs = ["Change Oil", 'Replace Oil Filter', "Install Spark Plugs"]; document.write('<h2>' + title + '</h2>'); document.write('<ul>'); do { document.write('<li>' + jobs[counter] + '</li>'); counter++; } while (counter < jobs.length) document.write('</ul>'); } var repairCompleted = true; if (repairCompleted == true) { prepare("Jobs Performed", []); } </script> </body> </html>
This would produce:
Consider the following code:
function prepare(jobs) { } var labor; prepare(labor);
Nothing in this code indicates the type of the argument. This means that, in the body of the function, the argument can be treated as anything, an array or not. This is one of beauties but also difficulties of JavaScript as a non-compiled language. In this case, if you have an array when calling the function, you can pass the array as argument. Then, in the body of the function, you can treat the argument as an array. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>College Park Auto-Repair</title> </head> <body> <h1>College Park Auto-Repair</h1> <script> function prepare(title, jobs) { var counter = 0; document.write(''); document.write('<h2>' + title + '</h2>'); document.write('<ul>'); do { document.write('<li>' + jobs[counter] + '</li>'); counter++; } while (counter < jobs.length) document.write('</ul>'); } var labor = [ "Checked Water Pump", "Replaced Wiper Blades", "Adjusted Timing Belt", "Replaced Left Lower Ball Ring" ]; prepare("Jobs Performed", labor); </script> </body> </html>
This would produce:
From now on, remember that if you are calling a function that takes an array but you don't (yet) have values for the array/argument, you can pass othe argument with empty parentheses.
JavaScript and Strings
Introduction
As you may know already, to declare a variable in JavaScript, you use the var keyword. To make it a string, initiaalize it with a value in either single-quotes or double-quotes.
A String in a String
Quoting a string consists of including one string in another string. In JavaScript, you have various solutions. In C-based languages, to distinguish a double-quote in another quote, you precede the internal quote with a backslash.
In JavaScript, if you create a string in single-quotes, to include another string in it, put the internal string in double-quotes. If you create a string in double-quotes, to include another string in it, put the internal string in single-quotes.
A String Class
To support strings, the JavaScript language provides a class named String. The class is equipped with various properties and methods to help you create and manage strings. Both the String class and the JavaScript language provide everything necessary to perform all types of operations on strings.
Arrays and Objects
As seen in C#, when you declare a string variable in JavaScript, you in fact get an object that is an array of characters. Each character occupies a specific position as its index in the array.
An Array from the Properties of an Object
We saw that, to create an object in JavaScript, you use the curly brackets to a variable and create a list of the members in the body of the object. We saw that each property is created using the following formula:
element-name : element-value
Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toys Store</title> </head> <body> <h1>Children Toys Store</h1> <form name="ChildrenToys" method="get"> <table> <tr> <td>Toy Name:</td> <td><input type="text" name="toyName" /></td> </tr> <tr> <td>Category:</td> <td><input type="text" name="category" /></td> </tr> <tr> <td>Unit Price:</td> <td><input type="text" name="unitPrice" /></td> </tr> </table> </form> <script> var toy = { toyName: "City Building Set", category: "Building Blocks", unitPrice: 18.75 }; document.ChildrenToys.toyName.value = toy.toyName; document.ChildrenToys.category.value = toy.category; document.ChildrenToys.unitPrice.value = toy.unitPrice; </script> </body> </html>
When you have added properties to an object, those properties are treated as elements of an array, and the array is to object. The property is made in two parts separated by a colon. The part on the left of the colon is the name of the property, also considered a key. The part on the right side is the value of the property. The name or key of a property/element can be almost anything. It can be an integer, a symbol, a string, etc. If the key is:
Here are examples:
var toy = { a: 6, ToyName: "City Building Set", 'Difficulty': "Mild", true : true, Category: "Building Blocks", "#": 137, 0: 0803845, 18.75: 18.75 };
To access the members of the object, if the key is:
To access a member as done for an array, apply the square brackets to the object. Then:
Here are examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<h1>Children Toys Store</h1>
<form name="ChildrenToys" method="get">
<table>
<tr>
<td>Item #:</td>
<td><input type="text" name="itemNumber" /></td>
</tr>
<tr>
<td>Toy Name:</td>
<td><input type="text" name="toyName" /></td>
</tr>
<tr>
<td>Category:</td>
<td><input type="text" name="category" /></td>
</tr>
<tr>
<td>Age Range:</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td>Unit Price:</td>
<td><input type="text" name="unitPrice" /></td>
</tr>
<tr>
<td>Number of Pieces:</td>
<td><input type="text" name="pieces" /></td>
</tr>
<tr>
<td>Difficulty Level:</td>
<td><input type="text" name="difficulty" /></td>
</tr>
<tr>
<td>Currently Available:</td>
<td><input type="text" name="availability" /></td>
</tr>
<tr>
<td>Warning:</td>
<td><input type="text" name="supervision" /></td>
</tr>
</table>
</form>
<script>
var toy = {
a: 6,
ToyName: "City Building Set",
'Difficulty': "Mild",
true : true,
Category: "Building Blocks",
"#": 137,
0: 0803845,
18.75: 18.75,
false : "Requires Supervision"
};
document.ChildrenToys.pieces.value = toy["#"]/span>;
document.ChildrenToys.itemNumber.value = toy[0]/span>;
document.ChildrenToys.category.value = toy.Category;
document.ChildrenToys.age.value = toy.a + "+";
document.ChildrenToys.availability.value = toy[true]/span>;
document.ChildrenToys.toyName.value = toy["ToyName"]/span>;
document.ChildrenToys.unitPrice.value = toy[18.75]/span>;
document.ChildrenToys.difficulty.value = toy.Difficulty;
document.ChildrenToys.supervision.value = toy.false;
</script>
</body>
</html>
}
To access the properties using a loop, use the square brackets of an array. In this case, the key is the variable of the loop. Therefore, apply the square brackets to the object and pass the index. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toys Store</title> </head> <body> <h1>Children Toys Store</h1> <script> var toy = { itemNumber: 538405, toyName: "High Speed Train", categories: "Mild", true : true, Category: "Building Blocks", "#": 137, 0: 0803845, 18.75: 18.75, false : "Requires Supervision" }; document.write("<ul>"); for (var play in toy) { document.write("<li>" + play + " : " + toy[play] + "</li>"); } document.write("</ul>"); </script> </body> </html>
An Array as a Property
A property of an array can be created as an array. You can use any of the techniques we have used so far to create the array. Here is an example:
var toy = {
itemNumber: 538405,
toyName: "High Speed Train",
categories: [ "Assembly", "Vehicles", "Reading", "Colors" ],
unitPrice: 32.50
};
To access a property of the object, use any of the techniques we reviewed. If you want to access the whole array as one object, use the name of the property. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toys Store</title> </head> <body> <h1>Children Toys Store</h1> <form name="ChildrenToys" method="get"> <table> <tr> <td style="font-weight: 600; width: 100px">Item #:</td> <td><span class="itemNumber"></span></td> </tr> <tr> <td style="font-weight: 600">Toy Name:</td> <td><span class="toyName"></span></td> </tr> <tr> <td style="font-weight: 600">Category:</td> <td><span class="category"></span></td> </tr> <tr> <td style="font-weight: 600">Unit Price:</td> <td><span class="unitPrice"></span></td> </tr> </table> </form> <script> var toy = {}; toy.itemNumber = 538405; toy.toyName = "High Speed Train"; valuetoy.categories = ["Assembly", "Vehicles", "Reading", "Colors"]; toy.unitPrice = 32.50; document.querySelector('.itemNumber').innerHTML = toy.itemNumber; document.querySelector('.toyName').innerHTML = toy.toyName; document.querySelector('.category').innerHTML = toy.categories; document.querySelector('.unitPrice').innerHTML = toy.unitPrice.toFixed(2); </script> </body> </html>
Of course, you can also create the object using the object and apply the rules and suggestions of that keyword. Here is an example:
<script> var toy = this; this.itemNumber = 538405; this.toyName = "High Speed Train"; this.categories = ["Assembly", "Vehicles", "Reading", "Colors"]; this.unitPrice = 32.50; document.querySelector('.itemNumber').innerHTML = toy.itemNumber; document.querySelector('.toyName').innerHTML = toy.toyName; document.querySelector('.category').innerHTML = toy.categories; document.querySelector('.unitPrice').innerHTML = toy.unitPrice.toFixed(2); </script>
An Array of Objects
The element of an array can be an object. You can first create an object and add it to an array. Here is an example:
var cts = {
itemNumber : 297495,
toyName: "City Building Set",
unitPrice: 18.75 };
var toys = [ cts ];
In the same way, you can create various objects, add each to an array, and separate them with commas. Here is an example:
var cts = {
itemNumber : 297495,
toyName: "City Building Set",
unitPrice: 18.75 };
var hst = {};
hst.itemNumber = 538405,
hst.toyName = "High Speed Train";
hst.unitPrice = 32.50;
var wh = {
itemNumber : 728174,
toyName: "Wooden House",
unitPrice: 24.92 };
var pas = {
itemNumber : 379705,
toyName: "Paper Animals Set",
unitPrice: 44.86 };
var toys = [ hst , cts, pas, wh ];
Instead of first defining the objects, you can create them directly in the array. To do this, in the square brackets of the array, start each element with { and end it with }. Separate them with commas. Here is an example is:
var toys = [{ itemNumber : 538405, toyName : "High Speed Train", unitPrice : 32.50 }, { itemNumber: 297495, toyName: "City Building Set", unitPrice: 18.75 }, { itemNumber: 379705, toyName: "Paper Animals Set", unitPrice: 44.86 }, { itemNumber: 728174, toyName: "Wooden House", unitPrice: 24.92 } ];
Once again, to access an element of an array, you can use the square brackets. For it comes to an array of objects, include the index of the desired object. This would give you access to the whole object at that index. If you want to access a member of the object, after the square brackets, type a period and the name of the member. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toys Store</title> </head> <body> <h1>Children Toys Store</h1> <form name="ChildrenToys" method="get"> <table> <tr> <td style="font-weight: 600; width: 100px">Item #:</td> <td><input type="text" name="itemNumber" /></td> </tr> <tr> <td style="font-weight: 600">Toy Name:</td> <td><input type="text" name="toyName" /></td> </tr> <tr> <td style="font-weight: 600">Unit Price:</td> <td><input type="text" name="unitPrice" /></td> </tr> </table> </form> <script type="text/javascript"> var hst = { itemNumber: 538405, toyName: "High Speed Train", unitPrice: 32.50 }; var cbs = {}; cbs.itemNumber = 297495; cbs.toyName = "City Building Set"; cbs.unitPrice = 18.75; var pas = { itemNumber: 379705, toyName: "Paper Animals Set", unitPrice: 44.86 }; var wh = {}; wh.itemNumber = 728174; wh.toyName = "Wooden House"; wh.unitPrice = 24.92; var toys = [ hst, cbs, pas, wh ]; document.ChildrenToys.itemNumber.value = toys[2].itemNumber; document.ChildrenToys.toyName.value = toys[2].toyName; document.ChildrenToys.unitPrice.value = toys[2].unitPrice.toFixed(2); </script> </body> </html>
To access each object of the array, you can use a loop (while, do...while, or for). Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toys Store</title> </head> <body> <h1 style="text-align: center">Children Toys Store</h1> <script type="text/javascript"> var hst = { itemNumber: 538405, toyName: "High Speed Train", unitPrice: 32.50 }; var cbs = {}; cbs.itemNumber = 297495; cbs.toyName = "City Building Set"; cbs.unitPrice = 18.75; var pas = { itemNumber: 379705, toyName: "Paper Animals Set", unitPrice: 44.86 }; var wh = {}; wh.itemNumber = 728174; wh.toyName = "Wooden House"; wh.unitPrice = 24.92; var toys = [ hst, cbs, pas, wh ]; var counter = 0; document.write("<table border='4' style='margin: auto; width: 400px;'>"); document.write("<tr>"); document.write("<td style='font-weight: 600; width: 100px'>Item #</td>"); document.write("<td style='font-weight: 600'>Toy Name</td>"); document.write("<td style='font-weight: 600'>Unit Price</td>"); document.write("</tr>"); do { document.write("<tr>"); document.write("<td>" + toys[counter].itemNumber + "</td>"); document.write("<td>" + toys[counter].toyName + "</td>"); document.write("<td>" + toys[counter].unitPrice.toFixed(2) + "</td>"); document.write("</tr>"); counter++; } while (counter < toys.length); </script> </body> </html>
When it comes to loops, probably a more practical option is the for...in combination. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Children Toys Store</title> </head> <body> <h1 style="text-align: center">Children Toys Store</h1> <script type="text/javascript"> . . . No Change var toys = [ hst, cbs, pas, wh ]; document.write("<table border='4' style='margin: auto; width: 400px;'>"); document.write("<tr>"); document.write("<td style='font-weight: 600; width: 100px'>Item #</td>"); document.write("<td style='font-weight: 600'>Toy Name</td>"); document.write("<td style='font-weight: 600'>Unit Price</td>"); document.write("</tr>"); for (var play in toys) { document.write("<tr>"); document.write("<td>" + toys[play].itemNumber + "</td>"); document.write("<td>" + toys[play].toyName + "</td>"); document.write("<td>" + toys[play].unitPrice.toFixed(2) + "</td>"); document.write("</tr>"); } </script> </body> </html>
|
||
Previous | Copyright © 2018-2019, FunctionX | Home |
|