Introduction to Arrays
Introduction to Arrays
Fundamentnals of Arrays
Introduction
An array is a technique to represent items, also referred to as elements.
Practical Learning: Introducing Arrays
Creating an Array
The TypeScript language simply follows the rules of arrays of JavaScript. TypeScript doesn't add much to arrays but takes more advantage of them than JavaScript does. In JavaScript, there are various ways to create and manage an array but the primary formula to follow is:
var | let variable-name = [];
Start with the var or the let keyword followed by a name. The name follows the rules of names of variables. Assign the square brackets to the name and end the statement with a semicolon. Here is an example:
let numbers = [];
The Type of an Array
In JavaScript, an array can contain anything. In TypeScript, it is usually a good idea to control the types of items that an array must contain. To control that aspect of an array, you should specify its type. To do this, after the name of the variable, type a colon, the desired data type, and square brackets. Here is an example:
let itemsNumbers: number[] = [];
An Array with an Element
An array is some type of a list. At a minimum, you can create it with one item. To do this, put the item in the (right) square brackets. If the item is a number, type it. Here is an example:
let itemNumber : number[] = [975974];
If the array will contain a Boolean value, set the value as true or false. Here is an example:
let drivingPeopleCrazy: boolean[] = [true];
If the element is a symbol, a letter of a string, include it in single or double-quotes. Here are examples:
let itemName: string[] = ['Khaki Pants']; let currency: string[] = ["$"];
An Array With Many Elements
Indeed, an array is a list of items. When creating an array, to specify its list of items, put them in the square brackets. Separate them with commas. The formula to follow is:
var | let variable-name : data-type = [eleament_1, eleament_2], ..., eleament_n];
Practical Learning: Creating Arrays
let numbers: number[] = [950835, 480583, 705804]; let names: string[] = ["Fire Truck with Remote Control", '612 Pieces Building Kit', '3-Pack Dinosaur Set']; let prices: number[] = [25.50, 55.55, 44.75]; let batteries: boolean[] = [true, false, false];
Accessing an Array
Introduction
Although an array is a list of items, you can access it as a whole. To do that, use the name of the array the same way you access a variable.
View: ItemInventory.cshtml
@{ ViewBag.Title = "Thai Restaurant"; } <h2>Thai Restaurant</h2> <p id="food"></p> <script src="~/Scripts/MenuPresentation.js"></script>
TypeScript File: MenuPresentation.ts
let thaiFood: string[] = ['Yum Neau', 'Curry Puffs', 'Tom Kha Soup', 'Shrimp Bikini']; document.querySelector("#food").innerHTML = thaiFood.toString();
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
The elements of an array are arranged in the order they are added to the list. Each item has an index which is its position. The indexes are zero-based. This means that the first item uses position 0. The second element is at position 1, and so on.
To access an element from an array, type the name of the array followed square brackets. In the square brackets, enter the zero-based index of the desired item. Here is an array:
View: FoodMenu.cshtml
@{ ViewBag.Title = "Thai Restaurant"; } <h2>Thai Restaurant</h2> <ul style="list-style-type: none;"> <li id="first"></li> <li id="second"></li> <li id="third"></li> <li id="fourth"></li> </ul> <script src="~/Scripts/MenuPresentation.js"></script>
TypeScript File: MenuPresentation.ts
let thaiFood: string[] = ['Yum Neau', 'Curry Puffs', 'Tom Kha Soup', 'Shrimp Bikini']; document.querySelector("#first").innerHTML = thaiFood[0]; document.querySelector("#second").innerHTML = thaiFood[1]; document.querySelector("#third").innerHTML = thaiFood[2]; document.querySelector("#fourth").innerHTML = thaiFood[3];
This would produce:
Practical Learning: Accessing an Array
let numbers: number[] = [950835, 480583, 705804];
let names: string[] = ["Fire Truck with Remote Control", '612 Pieces Building Kit', '3-Pack Dinosaur Set'];
let prices: number[] = [25.5, 55.55, 44.7];
let batteries: boolean[] = [true, false, false];
document.querySelector("#toy1Name").innerHTML = names[0];
document.querySelector("#toy1Price").innerHTML = prices[0].toFixed(2);
document.querySelector("#toy1Number").innerHTML = numbers[0].toString();
document.querySelector("#toy1Batteries").innerHTML = batteries[0].toString();
document.querySelector("#toy2Name").innerHTML = names[1];
document.querySelector("#toy2Price").innerHTML = prices[1].toFixed(2);
document.querySelector("#toy2Number").innerHTML = numbers[1].toString();
document.querySelector("#toy2Batteries").innerHTML = batteries[1].toString();
document.querySelector("#toy3Name").innerHTML = names[2];
document.querySelector("#toy3Price").innerHTML = prices[2].toFixed(2);
document.querySelector("#toy3Number").innerHTML = numbers[2].toString();
document.querySelector("#toy3Batteries").innerHTML = batteries[2].toString();
using System.Web.Mvc;
namespace ToysStore1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult ToyPresentation() => View();
}
}
@{ ViewBag.Title = "Toys Presentation"; } <h2>Toys Presentation</h2> <hr /> <table style="width: 500px;"> <tr> <td style="border: 1px solid #C0C0C0; width: 80px; font-weight: 600">Product #</td> <td style="border: 1px solid #C0C0C0; font-weight: 600">Toy Name/Description</td> <td style="border: 1px solid #C0C0C0; width: 60px; font-weight: 600">Price</td> <td style="border: 1px solid #C0C0C0; width: 140px; font-weight: 600">Require Batteries</td> </tr> <tr> <td style="border: 1px solid #C0C0C0;" id="toy1Number"></td> <td style="border: 1px solid #C0C0C0;" id="toy1Name"></td> <td style="border: 1px solid #C0C0C0;" id="toy1Price"></td> <td style="border: 1px solid #C0C0C0;" id="toy1Batteries"></td> </tr> <tr> <td style="border: 1px solid #C0C0C0;" id="toy2Number"></td> <td style="border: 1px solid #C0C0C0;" id="toy2Name"></td> <td style="border: 1px solid #C0C0C0;" id="toy2Price"></td> <td style="border: 1px solid #C0C0C0;" id="toy2Batteries"></td> </tr> <tr> <td style="border: 1px solid #C0C0C0;" id="toy3Number"></td> <td style="border: 1px solid #C0C0C0;" id="toy3Name"></td> <td style="border: 1px solid #C0C0C0;" id="toy3Price"></td> <td style="border: 1px solid #C0C0C0;" id="toy3Batteries"></td> </tr> </table> <script src="~/Scripts/ToyExamination.js"></script>
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.
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:
View: FoodMenu.cshtml
@{ ViewBag.Title = "Thai Restaurant"; } <h2>Thai Restaurant: Food Menu</h2> <ul style="list-style-type: none;"> <li id="first"></li> <li id="second"></li> <li id="third"></li> <li id="fourth"></li> <li id="fifth"></li> </ul> <script src="~/Scripts/MenuPresentation.js"></script>
TypeScript File: MenuPresentation.ts
let thaiFood: string[] = ['Yum Neau', 'Curry Puffs', 'Tom Kha Soup', 'Shrimp Bikini'];
thaiFood[4] = "Chicken Cashew";
document.querySelector("#first").innerHTML = thaiFood[0];
document.querySelector("#second").innerHTML = thaiFood[1];
document.querySelector("#third").innerHTML = thaiFood[2];
document.querySelector("#fourth").innerHTML = thaiFood[3];
document.querySelector("#fifth").innerHTML = thaiFood[4];
This would produce:
Updating an Element
Updating an element consists of changing its value. This feature is available in all arrays of the C-based languages, including JavaScript. 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:
let thaiFood: string[] = ['Yum Neau', 'Curry Puffs',
'Tom Kha Soup', 'Shrimp Bikini'];
thaiFood[4] = "Chicken Cashew";
thaiFood[3] = "Kao Pad Nam Prik Pao";
thaiFood[1] = 'Curried Noddles with Chicken';
document.querySelector("#first").innerHTML = thaiFood[0];
document.querySelector("#second").innerHTML = thaiFood[1];
document.querySelector("#third").innerHTML = thaiFood[2];
document.querySelector("#fourth").innerHTML = thaiFood[3];
document.querySelector("#fifth").innerHTML = thaiFood[4];
This would produce:
Arrays and Objects
An Array from the Properties of an Object
We saw that, to create an object in JavaScript, you add 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:
let truck = { itemNumber: 950835, name: "Fire Truck with Remote Control", price: 25.5, batteriesRequired: true };
When you have added properties to an object, those properties are treated as elements of an array, and the array is an 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:
let 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:
TypeScript File: ToyExamination.ts:
let toy = { a: 6, ToyName: "City Building Set", 'Difficulty': "Mild", true: true, Category: "Building Blocks", "#": 137, 0: 803845, 18.75: 18.75, false: "Requires Supervision" }; document.querySelector("#age").innerHTML = toy.a.toString(); document.querySelector("#toyName").innerHTML = toy.ToyName; document.querySelector("#category").innerHTML = toy.Category; document.querySelector("#difficulty").innerHTML = toy.Difficulty; document.querySelector("#pieces").innerHTML = toy["#"].toString(); document.querySelector("#itemNumber").innerHTML = toy[0].toString(); document.querySelector("#unitPrice").innerHTML = toy[18.75].toFixed(2); document.querySelector("#availability").innerHTML = toy["true"].toString(); document.querySelector("#supervision").innerHTML = toy.false;
View: ToyPresentation.cshtml
@{ ViewBag.Title = "Toy Presentation"; } <h2>Toy Presentation</h2> <hr /> <table> <tr> <td style="width:150px; font-weight: 600;">Item #:</td> <td><span id="itemNumber"></span></td> </tr> <tr> <td><b>Toy Name:</b></td> <td><span id="toyName"></span></td> </tr> <tr> <td><b>Category:</b></td> <td><span id="category"></span></td> </tr> <tr> <td><b>Age Range:</b></td> <td><span id="age"></span></td> </tr> <tr> <td><b>Unit Price:</b></td> <td><span id="unitPrice"></span></td> </tr> <tr> <td><b>Number of Pieces:</b></td> <td><span id="pieces"></span></td> </tr> <tr> <td><b>Difficulty Level:</b></td> <td><span id="difficulty"></span></td> </tr> <tr> <td><b>Currently Available:</b></td> <td><span id="availability"></span></td> </tr> <tr> <td><b>Warning:</b></td> <td><span id="supervision"></span></td> </tr> </table> <script src="~/Scripts/ToyExamination.js"></script>
This would produce`
An Array as a Property
A property of an array can be created as an array. to do this, in the body of the object, specify the name of the property, a colon, and square brackets. If the value of the property is empty, leave the square brackets empty. If the array needs only one value, enter it. If the array must use many elements, put them in the square brackets and separate them with commas. Here is an example:
var toy = {
itemNumber: 538405,
toyName: "High Speed Train",
requiresBatteries: true,
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.
Of course, you can also create the object using the this object and apply the rules and suggestions of that keyword. Here is an example:
let 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);
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:
let cts = {
itemNumber : 297495,
toyName: "City Building Set",
requiresBatteries: true,
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:
let cts = {
itemNumber : 297495,
toyName: "City Building Set",
requiresBatteries: true,
unitPrice: 18.75 };
let hst = {
itemNumber : 538405,
toyName : "High Speed Train",
unitPrice : 32.50 };
let wh = {
itemNumber : 728174,
toyName: "Wooden House",
unitPrice: 24.92 };
let pas = {
itemNumber : 379705,
toyName: "Paper Animals Set",
unitPrice: 44.86 };
let 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:
let 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.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2018-2019, FunctionX | Next |
|