- •Introduction
- •1 Working with javascript objects and arrays
- •JavaScript is an Interpreted Language
- •1.2 JavaScript History Object, Working with JavaScript Objects and Arrays (JavaScript)
- •Intrinsic objects, such as Array and String.
- •Arrays as Objects. In JavaScript, objects and arrays are handled almost identically, because arrays are merely a special kind of object. Both objects and arrays can have properties and methods.
- •Create an Array in JavaScript. Here is an example, shows how to create an array in JavaScript:
- •Display Array Element in JavaScript. Here is an example, shows how to display/print array element in JavaScript:
- •2 Reports using objects and arrays javascript
- •2.1 Specify a reference to the result of the report, which appeared in arrays of javascript
Intrinsic objects, such as Array and String.
Objects you create.
Host objects, such as window and document.
ActiveX objects.
Expando Properties and Methods. All objects in JavaScript support expando properties and methods, which can be added and removed at run time. These properties and methods can have any name and can be identified by numbers. If the name of the property or method is a simple identifier, it can be written after the object name with a period, such as myObj.name, myObj.age, and myObj.getAge in the following code:
var myObj = new Object();
myObj.name = "Fred";
myObj.age = 42;
myObj.getAge =
function () {
return this.age; };
document.write(myObj.name);
document.write("<br/>");
document.write(myObj.age);
document.write("<br/>");
document.write(myObj.getAge());
// Output:
// Fred
// 42
// 42
If the name of the property or method is not a simple identifier or is unknown at the time you write the script, you can use an expression inside square brackets to index the property. The names of all expando properties in JavaScript are converted to strings before being added to the object.
var myObj = new Object();
// Add two expando properties that cannot be written in the
// object.property syntax.
// The first contains invalid characters (spaces), so must be
// written inside square brackets.
myObj["not a valid identifier"] = "This is the property value";
// The second expando name is a number, so it also must
// be placed inside square brackets
myObj[100] = "100";
For information about creating an object from a definition, see Creating Objects.
Arrays as Objects. In JavaScript, objects and arrays are handled almost identically, because arrays are merely a special kind of object. Both objects and arrays can have properties and methods.
Arrays have a length property but objects do not. When you assign a value to an element of an array whose index is greater than its length (for example, myArray[100] = "hello"), the lengthproperty is automatically increased to the new length. Similarly, if you make the length property smaller, any element whose index is outside the length of the array is deleted.
// An array with three elements
var myArray = new Array(3);
// Add some data
myArray[0] = "Hello";
myArray[1] = 42;
myArray[2] = new Date(2000, 1, 1);
document.write("original length is: " + myArray.length);
document.write("<br/>");
// Add some expando properties
myArray.expando = "JavaScript!";
myArray["another Expando"] = "Windows";
// This will still display 3, since the two expando properties
// don't affect the length.
document.write("new length is : " + myArray.length);
// Output:
// original length is: 3
// new length is : 3
Arrays provide methods to iterate over and manipulate members. The following example shows how to obtain the properties of objects stored in an array.
var myArray = new Array(3);
// Add some data
for(var i = 1; i <= 3; i++) {
myArray[i] = new Date(2000 + i, 1, 1); }
myArray.forEach(function (item) {
document.write(item.getFullYear()); });
// Output:
// 2001
// 2002
// 2003
Multi-Dimensional Arrays. JavaScript does not directly support multi-dimensional arrays, but you can get the behavior of multi-dimensional arrays by storing arrays within the elements of another array. (You can store any sort of data inside array elements, including other arrays.) For example, the following code builds a multiplication table for the numbers up to 5.
// The size of the table.
var iMaxNum = 5;
// Loop counters.
var i, j;
// Set the length of the array to iMaxNum + 1.
// The first array index is zero, not 1.
var MultiplicationTable = new Array(iMaxNum + 1);
// Loop for each major number (each row in the table)
for (i = 1; i <= iMaxNum; i++)
{
// Create the columns in the table
MultiplicationTable[i] = new Array(iMaxNum + 1);
// Fill the row with the results of the multiplication
for (j = 1; j <= iMaxNum; j++)
{
MultiplicationTable[i][j] = i * j; } }
document.write(MultiplicationTable[3][4]);
document.write("<br/>");
document.write(MultiplicationTable[5][2]);
document.write("<br/>");
document.write(MultiplicationTable[1][4]);
// Output:
// 12
// 10
// 4
Arrays. An array is a set of elements, which are accessed by index. An array is created using the new operator and the array constructor - function Array. Suppose you want to create an array of user names. Thiscanbedoneasfollows:
var users = new Array("Artem", "Irina", "Sergey", "Boris");
This statement creates an array of 4 elements (users). All the elements of the array are numbered starting from zero. To get the value of the array element you need to specify the name of the array and in square brackets the atomic number (the index). So, to gain access to the first element of our array, you could write:
users[0]
The values of the array does not necessarily give at once. For example, it is possible to take advantage of such construction:
varusers = newArray(4);
This expression also creates an array of four elements, but the values of the elements can be specified later by using the assignment operator:
users[0] = "Artem"; users[1] = "Irina"; users[2] = "Sergey"; users[3] = "Boris";
And finally, you can use the constructor without parameters:
varusers = newArray();
In this case, we specify that created variable users will be the array, whose size will be determined automatically as the elements come. To determine the length of the array (ie, the number of elements in it) the property length is used. For example, access to the last element of the array (if we do not know how many elements in it) as follows:
users[users.length-1];
I.e. first determined the length of the array (users.length), then, mindful of the fact that the numbering of the elements begins with zero, 1 is subtracted from the length; and the resulting value is used as an array index. Here's an example: suppose we want when the page is loaded the user could to see which day of the week today. Code html-pages is as follows:
<html>
<head>
<title>javascript массивы</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="showDay();">
</body>
</html>
* Earlier we have considered the events and their handlers. In this case, we will use the event Load (document is loaded in the browser) and its handler - onload. In other words, our function showDay () should be triggered when the document loads. *
Now let’s write the function showDay():
Function showDay() {
varnDays=newArray("воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота");
var now=new Date();
var day=now.getDay();
variDay=nDays[day];
varstr="Сегодня - " + iDay;
document.write(str);}
Let’s consider in detail. First, we create an array nDays of seven elements (in the previous lesson, we talked about that zero corresponds to “воскресенье”):
Var nDays=newArray("воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота");
Then, from the current date we get the current day of the week (its numeric equivalent):
var now=new Date();
var day=now.getDay();
and we use it as an index to access the element in the array:
var iDay=nDays[day];
The last two lines form and reflect the result of:
Var str="Сегодня - " + iDay;
document.write(str);
Try to work the script in action and make sure that when the page loads, there is a phrase such as "Today - Friday". Let’s continue. The two arrays can be combined into one using the method concat (). Suppose we have two massiva A and B, and we want them to be combined into one - c :
var a=new Array(1, 2, 3);
var b=new Array(4, 5, 6);
var c=a.concat(b);
At the output we obtain an array C of six elements 1, 2, 3, 4, 5, 6.
The arrays can be sorted using the method sort(), is true only in the lexicographical order (ie, as a string).
For example, if you apply the sort() method to the array with the names:
var users = new Array("Artem", "Irina", "Sergey", "Boris");
var c=users.sort();
at the output we obtain an array C: Artem, Boris, Irina, Sergey. And if you apply the sort() method to the array with the numbers:
var n = new Array(11, 12, 10, 107, 3, 20, 25, 101, 14, 34, 44, 5, 4);
var c=n.sort();
then at the output we obtain the following array: 10, 101, 107, 11, 12, 14, 20, 25, 3, 34, 4, 44, 5.
I.e. elements are compared as string and not as a number. So apply the sort () method should be cautious. We now consider an example of how to search for a specific item in the array. Suppose we have an array of 6 names, and we want to know whether there is in it a certain name.
Code html-pages is simple:
<html>
<head>
<title>javascript Arrays</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="forma10">
Enter a name for the test:
<input type="text" size="20" name="name">
<input type="button" value="Проверить" onClick="proverka(forma10);">
</form>
</body>
</html>
Let’s write the function proverka() on the page script.js:
Function proverka(obj) {
var k;
var users = new Array("Artem", "Irina", "Sergey", "Boris", "Olga", "Viktor");
var n=obj.name.value;
for (var i=0; i<=users.length-1; i++){
if (users[i]==n)
{k=0; break}}
if (k==0){alert("This name is in array.")}
else {alert("There is no such name in the array .")}}
Here we have used an algorithm called linear search, according to which all the elements of an array of users are compared alternately with the sample (with n, i.e., the name that is entered by the user).
If the next element is the same as the sample, then the problem is solved (the cycle is interrupted). If the desired name is not in the array, we learn about it when we have looked all the elements of the array.
Task: write the script that will determine the maximal element of the numeric array. JavaScript arrays are basically used in storing multiple values in a single variable.
